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