Reputation: 123
Can anyone help me with creating a regex for variables in java so that the string variable will be considered to be a case insensitive and replace each and every word like Access, access, etc with WINDOWS of any thing like that?
This is the code:
$html=html.replaceAll(label, "WINDOWS");
Notice that label is a string variable.
Upvotes: 8
Views: 17802
Reputation: 425288
Just add the "case insensitive" switch to the regex:
html.replaceAll("(?i)"+label, "WINDOWS");
Note: If the label could contain characters with special regex significance, eg if label was ".*"
, but you want the label treated as plain text (ie not a regex), add regex quotes around the label, either
html.replaceAll("(?i)\\Q" + label + "\\E", "WINDOWS");
or
html.replaceAll("(?i)" + Pattern.quote(label), "WINDOWS");
Upvotes: 26
Reputation: 15
I think but am not sure you want label to be something like [Aa][cC][cC][eE][sS][sS]
or alternatively do
html = Pattern.compile(lable, Pattern.CASE_INSENSITIVE)
.matcher(html).replaceAll("WINDOWS");
Upvotes: -1
Reputation: 7779
String.replaceAll is equivalent to creating a matcher and calling its replaceAll method so you can do something like this to make it case insensitive:
html = Pattern.compile(label, Pattern.CASE_INSENSITIVE).matcher(html).replaceAll("WINDOWS");
See: String.replaceAll and Pattern.compile JavaDocs
Upvotes: 8
Reputation: 11950
Just use patterns and matcher. Here's the code
Pattern p = Pattern.compile("Your word", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("String containing words");
String result = m.replaceAll("Replacement word");
Using patterns is easy as they are not case insensitive.
For more information, see
Matchmaking with regular expressions
Upvotes: 1