8

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.

DhruvPatel
  • 123
  • 1
  • 2
  • 9

4 Answers4

26

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");
Bohemian
  • 412,405
  • 93
  • 575
  • 722
7

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

Bohemian
  • 412,405
  • 93
  • 575
  • 722
anttix
  • 7,709
  • 1
  • 24
  • 25
  • Is there a significant impact on memory / performance when using case insensitive (in opposition to Java's default case sensitive replace() method) for large Strings? For example, a document containing predefined labels (variables) that can be replaced dynamically based on some app logic. – Andrei F Feb 07 '17 at 08:26
1

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

n00begon
  • 3,503
  • 3
  • 29
  • 42
Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91
-1

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");
Shashank Kadne
  • 7,993
  • 6
  • 41
  • 54
blinkymomo
  • 15
  • 2