我有一个字符串,12999986, 31999999, 39949283, 99002999
我试图替换所有模式 99
图案为00
。但是,该模式不能是另一个类似字符串的子字符串的一部分,例如 999
或9999
。在此示例中,输出将为 12999986, 31999999, 30049283, 00002999
( 39949283
至 30049283
、 99002999
至 00002999
)。我已经创建了这个方法,但它实际上不适用于较大的字符串(未找到所有模式,在随机位置插入字符串):
public static String replaceAllExact(String data, String searchString, String replacement) {
List<Integer> locations = new ArrayList<>(); //start (exclusive)
char[] dataChars = data.toCharArray();
char[] searchStringChars = searchString.toCharArray();
char[] replacementChars = replacement.toCharArray();
int i = 0;
int k = 0;
int startIndex = 0;
int searchStringCharsLength = searchStringChars.length - 1;
for(char c : dataChars) {
if(c != searchStringChars[i] && i == 0) { //not the start of a pattern; continue
k++;
continue;
}else if(c == searchStringChars[i] && i == 0) { //might be the pattern we're looking for
startIndex = k;
i++;
}else if((c == searchStringChars[i] && i > searchStringCharsLength) || ((c != searchStringChars[i] && i < searchStringCharsLength) && i != 0)) { //pattern was too long or too short to be the pattern we're looking for
i = 0;
}else if(c == searchStringChars[i] && i < searchStringCharsLength) { //could be the pattern... keep going
i++;
}else if(c != searchStringChars[i] && i != 0 && i == searchStringCharsLength) { //this is the pattern we're looking for
locations.add(startIndex);
i = 0;
}
k++;
}
int offset = 0;
StringBuilder builder = new StringBuilder(data);
for(int l : locations) {
l += offset;
builder.delete(l, l + searchString.length());
builder.insert(l, replacementChars);
offset = (builder.length() - data.length());
}
return builder.toString();
}
我怎样才能做到这一点?如果可能的话,正则表达式解决方案将受到欢迎。
澄清
相似字符串是普通替换将替换其中某些字符的字符串。例如使用标准库replace(CharSequence target, CharSequence replacement)
,字符串 31999999
会被认为是相似的,因为 replace(99, 00)
可以替换一些字符。
字符串39349283
不是相似的字符串,因为 replace(99, 00)
不能替换任何字符。字符串39949283
类似,因为 replace(99, 00)
可以替换一些字符。
最佳答案
如果我理解正确的话,你想替换 99
与其他东西,但前提是没有 9
之前或之后。
在这种情况下,您可以使用 look-around机制并确保
- 没有
9
之前,通过(?<!9)
- 没有
9
之后,通过(?!9)
所以你可以使用str = str.replaceAll("(?<!9)99(?!9)", "00")
.
关于java - 仅替换不是相似字符串子串的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44686525/