Sunday 31 March 2019

regex - In Java Regular Expression "1" (back reference) is not working



I want to replace string "Cannot" with "Can not" and "cannot" with "can not". For that, I am using the code below:




 String string = "I Cannot do it.";
string = string.replaceAll("([Cc])annot", "\\1an not");


Desired string is "I Can not do it.".



String string = "I Cannot do it.";
string = string.replaceAll("([Cc])annot", "\\1an not");



Desired string is "I can not do it". In Ruby '\1' replaces a string with the matched character C or c (using back reference). I don't know what to use in Java. Below is the Ruby regex which works fine:



"I Cannot do it".gsub!(/([Cc])annot/,'\1an not')
# => "I Can not do it"
"I cannot do it".gsub!(/([Cc])annot/,'\1an not')
# => "I can not do it"

Answer



What about




String string = "I Cannot do it."
string = string.replaceAll("([Cc])annot","$1an not");

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...