Friday, 28 July 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"

Answer



What about



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

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...