Sunday, March 31, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...