DhruvPatel
DhruvPatel

Reputation: 123

Case Insensitive variable for String replaceAll(,) method Java

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

Answers (4)

Bohemian
Bohemian

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

blinkymomo
blinkymomo

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

anttix
anttix

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

Sri Harsha Chilakapati
Sri Harsha Chilakapati

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

Java: Pattern and Matcher

Upvotes: 1

Related Questions