是否有可能以其他格式编写replaceAll-regex?

时间:2013-07-30 15:22:59

标签: java regex

我的代码:

String stringTxt = "Hello World!!";
String negatorStr = "Loop";
String regexToUse="["+negatorStr.toLowerCase()+negatorStr.toUpperCase()+"]";
System.out.println(stringTxt.replaceAll(regexToUse, ""));


正如您可以看到的那样,目标是将“L”或“O”或“P”替换为“”(空)。并且代码通过以小写和大写形式表示negatorStr不区分大小写,并在“[”,“]”内组合两者以将其转换为与replaceAll()兼容的正则表达式。

问题:还有其他方法可以使negatorStr不区分大小写,以便我可以在replaceAll()中使用它吗?

4 个答案:

答案 0 :(得分:3)

在正则表达式的开头使用(?i)使其不区分大小写。

这将是

String regexToUse = "(?i)[" + negatorStr + "]";

您可以在Pattern类的字段摘要中查看其他可能的标记。

答案 1 :(得分:2)

是的,有两种方式。

使用内联标志:

final String replaced = myString.ReplaceAll("(?i)[lop]", "");

或者使用带有显式标志的PatternMatcher

final Pattern p = Pattern.compile("[lop]", Pattern.CASE_INSENSITIVE);
final String replaced = p.matcher("Hello World!!").replaceAll("");

输出:

He Wrd!!
He Wrd!!

答案 2 :(得分:1)

您可以在正则表达式中使用(?i)或使用模式和the Pattern.CASE_INSENSITIVE flag

String regexToUse = "[" + negatorStr.toLowerCase() + "]";
Pattern p = Pattern.compile(regexToUse, Pattern.CASE_INSENSITIVE);
System.out.println(p.matcher(stringTxt).replaceAll(""));

如果用相同的模式替换多个字符串,后者是有意义的,否则前者更短。

答案 3 :(得分:0)

  

目标是将“L”或“O”或“P”替换为“”(空)

String stringTxt = "Hello World!!";
System.out.println(stringTxt.replaceAll("(?i)(l|o|p)", ""));