Friday, 14 April 2017

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"

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...