简体   繁体   中英

Replace exact string with special characters and not the part of another substring

I am trying to replace the substring from a string like:

Sample string value '[1]T.1.v - Marriage Statement'!C10 and this

The text to replace is '[1]T.1.v - Marriage Statement'!C10 with some other string say var1 so that the string becomes Sample string value var1 and this . The problem is there can be strings with values like Sample string value '[1]T.1.v - Marriage Statement'!C101 and this where the replacement should not work. I was exploring the word boundary regex to limit the replacement:

String sample = "Value can be '[1]T.1.v - Marriage Statement'!C10 and this";
String a = sample.replaceAll("\\b'[1]T.1.v - Marriage Statement'!C10\\b", "var1");
System.out.println(a);

But this doesn't seem to replace the word at all. I tried simple string replace but that will replace the substring in Sample string value '[1]T.1.v - Marriage Statement'!C101 and this as well giving output as Sample string value var11 and this which is an error.

Any suggestions how can this be achieved?

删除前导\\b然后使用\\Q...\\E转义序列将输入字符串视为文字:

String a = sample.replaceAll("\\Q" + param +"\\E\\b", "var1");

Single quote is not considered a word boundary, so the initial \\\\b anchor prevents the rest of the text from matching.

Moreover, your text itself has a significant number of special characters, so it should be quoted with \\\\Q and \\\\E .

Here is a regex that fixes these shortcomings:

"(?<=\\s|^)\\Q'[1]T.1.v - Marriage Statement'!C10\\E(?=\\s|$)"

It replaces the initial \\\\b with (?<=\\\\s|^) , and the final \\\\b with (?=\\\\s|$) to allow for the target string to begin and end in non-word characters, such as quotes. Use of \\\\Q and \\\\E allows us to keep special characters in the rest of the target string unescaped.

Demo.

转义括号和点

'\[1\]T\.1\.v - Marriage Statement'!C10

Two things:

• change your \\\\' in your replaceAll to just \\'

• change replaceAll(... to replace(... (See bottom of post)

It should look like this:

public static void main(String[]args) {
    String sample = "Value can be '[1]T.1.v - Marriage Statement'!C10 and this";
    String a = sample.replace("\'[1]T.1.v - Marriage Statement\'!C10", "var1");
    System.out.println(a);
}

Yielding the output:

Value can be var1 and this

using replaceAll is better if you are replacing a bunch of occurances of something, such as the letter A. replace is good for replacing something if it is just one instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM