String replaceAll(,) 方法 Java 的不区分大小写的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11236610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Case Insensitive variable for String replaceAll(,) method Java
提问by DhruvPatel
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?
任何人都可以帮助我在 java 中为变量创建正则表达式,以便字符串变量将被视为不区分大小写,并将每个单词(如 Access、access 等)替换为 WINDOWS 之类的任何东西?
This is the code:
这是代码:
$html=html.replaceAll(label, "WINDOWS");
Notice that label is a string variable.
注意 label 是一个字符串变量。
回答by Bohemian
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
注意:如果标签可以包含具有特殊正则表达式意义的字符,例如如果 label was ".*"
,但您希望将标签视为纯文本(即不是正则表达式),请在标签周围添加正则表达式引号,或者
html.replaceAll("(?i)\Q" + label + "\E", "WINDOWS");
or
或者
html.replaceAll("(?i)" + Pattern.quote(label), "WINDOWS");
回答by anttix
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:
String.replaceAll 相当于创建一个匹配器并调用它的 replaceAll 方法,因此您可以执行以下操作以使其不区分大小写:
html = Pattern.compile(label, Pattern.CASE_INSENSITIVE).matcher(html).replaceAll("WINDOWS");
See: String.replaceAlland Pattern.compileJavaDocs
请参阅:String.replaceAll和 Pattern.compileJavaDocs
回答by Sri Harsha Chilakapati
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
有关更多信息,请参阅
回答by blinkymomo
I think but am not sure you want label to be something like [Aa][cC][cC][eE][sS][sS]
我认为但不确定您是否希望标签类似于 [Aa][cC][cC][eE][sS][sS]
or alternatively do
或者做
html = Pattern.compile(lable, Pattern.CASE_INSENSITIVE)
.matcher(html).replaceAll("WINDOWS");