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

后端 未结 4 1405
面向向阳花
面向向阳花 2020-12-19 05:36

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

from = \"\\\\b\" + from + \"\         


        
4条回答
  •  情深已故
    2020-12-19 06:14

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

    from = "(?

    See the regex demo.

    The (? 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 = "(? add, register1, $temp40, 42
    

提交回复
热议问题