用于String的AllInnsensitive变量replaceAll(,)方法Java

时间:2012-06-28 00:33:55

标签: java regex string

任何人都可以帮我在java中为变量创建一个正则表达式,这样字符串变量就会被认为是不区分大小写的,用WINDOWS替换每个单词如Access,access等等吗?

这是代码:

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

请注意,label是一个字符串变量。

4 个答案:

答案 0 :(得分:23)

只需将“不区分大小写”开关添加到正则表达式:

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

注意:如果标签可能包含具有特殊正则表达式重要性的字符,例如,如果标签为".*",但您希望标签被视为纯文本(即不是正则表达式),请在标签周围添加正则表达式引号,或者

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

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

答案 1 :(得分:7)

String.replaceAll等效于创建匹配器并调用其replaceAll方法,因此您可以执行类似这样的操作以使其不区分大小写:

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

请参阅:String.replaceAllPattern.compile JavaDocs

答案 2 :(得分:1)

只需使用模式和匹配器。这是代码

Pattern p = Pattern.compile("Your word", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("String containing words");
String result = m.replaceAll("Replacement word");

使用模式很容易,因为它们不区分大小写。

有关详细信息,请参阅

Matchmaking with regular expressions

Java: Pattern and Matcher

答案 3 :(得分:-1)

我想但我不确定你想要标签是[Aa][cC][cC][eE][sS][sS]

或者做

html = Pattern.compile(lable, Pattern.CASE_INSENSITIVE)
        .matcher(html).replaceAll("WINDOWS");
相关问题