Case-insensitive variable for String replaceAll (,) Java method

Can someone help me create a regex for variables in java so that the string variable is considered case insensitive and replace every word like Access, access, etc. with WINDOWS any similar thing?

This is the code:

$html=html.replaceAll(label, "WINDOWS"); 

Note that the label is a string variable.

+6
source share
4 answers

Just add the case insensitive switch to the regular expression:

 html.replaceAll("(?i)"+label, "WINDOWS"); 

Note. Caution when the label is the regular expression itself, for example, presenting the effect if the label was ".*"

+23
source

String.replaceAll is equivalent to creating a socket and calling its replaceAll method, so you can do something like this to make the case insensitive:

 html = Pattern.compile(label, Pattern.CASE_INSENSITIVE).matcher(html).replaceAll("WINDOWS"); 

See: String.replaceAll and Pattern.compile JavaDocs

+7
source

Just use templates and matches. Here is 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 templates is easy because they are not case sensitive.

For more information see

Matchmaking with regular expressions

Java: pattern and mapping

+1
source

I think, but not sure if you want the label to be something like [Aa][cC][cC][eE][sS][sS]

or alternatively

 html = Pattern.compile(lable, Pattern.CASE_INSENSITIVE) .matcher(html).replaceAll("WINDOWS"); 
0
source

Source: https://habr.com/ru/post/919198/


All Articles