Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

java - Matching a whole word with leading or trailing special symbols like dollar in a string

I can replace dollar signs by using Matcher.quoteReplacement. I can replace words by adding boundary characters:

from = "\b" + from + "\b"; 
outString = line.replaceAll(from, to);

But I can't seem to combine them to replace words with dollar signs.

Here's an example. I am trying to replace "$temp4" (NOT $temp40) with "register1".

        String line = "add, $temp4, $temp40, 42";
        String to = "register1";
        String from = "$temp4";
        String outString;


        from = Matcher.quoteReplacement(from);
        from = "\b" + from + "\b";  //do whole word replacement

        outString = line.replaceAll(from, to);
        System.out.println(outString);

Outputs

"add, $temp4, $temp40, 42"

How do I get it to replace $temp4 and only $temp4?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use unambiguous word boundaries, (?<!w) and (?!w), instead of that are context dependent:

from = "(?<!\w)" + Pattern.quote(from) + "(?!\w)";

See the regex demo.

The (?<!w) is a negative lookbehind that fails the match if there is a non-word char immediately to the left of the current location and (?!w) is a negative lookahead that fails the match if there is a non-word char immediately to the right of the current location. The Pattern.quote(from) is necessary to escape any special chars in the from variable.

See the Java demo:

String line = "add, $temp4, $temp40, 42";
String to = "register1";
String from = "$temp4";
String outString;

from = "(?<!\w)" + Pattern.quote(from) + "(?!\w)";

outString = line.replaceAll(from, to);
System.out.println(outString);
// => add, register1, $temp40, 42

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...