gre*_*lle 6 java regex replaceall
我想将所有"*"转换为".*",除了"\*"
String regex01 = "\\*toto".replaceAll("[^\\\\]\\*", ".*");
assertTrue("*toto".matches(regex01));// True
String regex02 = "toto*".replaceAll("[^\\\\]\\*", ".*");
assertTrue("tototo".matches(regex02));// True
String regex03 = "*toto".replaceAll("[^\\\\]\\*", ".*");
assertTrue("tototo".matches(regex03));// Error
Run Code Online (Sandbox Code Playgroud)
如果"*"是第一个出现错误的字符:java.util.regex.PatternSyntaxException:在索引0附近悬挂元字符'*'
什么是正确的正则表达式?
您需要在这里使用负向后查找:
String regex01 = input.replaceFirst("(?<!\\\\)\\*", ".*");
Run Code Online (Sandbox Code Playgroud)
(?<!\\\\)*是一个负向后查找,如果前面没有反斜杠则表示匹配。
例子:
regex01 = "\\*toto".replaceAll("(?<!\\\\)\\*", ".*");
//=> \*toto
regex01 = "*toto".replaceAll("(?<!\\\\)\\*", ".*");
//=> .*toto
Run Code Online (Sandbox Code Playgroud)