Home > Back-end >  How to make regex eol `$` to match ONLY "ending position of a String"?
How to make regex eol `$` to match ONLY "ending position of a String"?

Time:04-16

know:

$ Matches the ending position of the string or the position just before a string-ending newline. https://en.wikipedia.org/wiki/Regular_expression

ask:

How can I make $ to match ONLY "ending position of the string", NOT "or the position just before a string-ending newline"?

eg:

If you run

String str = "the first sentence\n"
             "the second sentence\n"
             "the third sentence\n";
    
System.out.println(str.replaceAll("$", "--"));

current behavior

Output will be

the first sentence
the second sentence
the third sentence--
--

desire behavior

Output desire to be

the first sentence
the second sentence
the third sentence
--

CodePudding user response:

You can use the "absolute end of string" construct \z

System.out.println(str.replaceAll("\\z", "--"));

See: Java regex constructs

  • Related