Alex Rivera | Logout

Case Insensitive variable for String replaceAll(,) method Java

Asked 2012-06-28T00:33:55.420
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.

Edit
Report

2 Answers

8

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

answered 2012-06-28T00:50:00.167
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

answered 2012-06-28T00:48:10.433

Your Answer