我需要一个可以与String类的replaceAll
方法一起使用的正则表达式,将*
的所有实例替换为.*
,除了尾随\
< / p>
即。转换将是
[any character]*[any character] => [any character].*[any character]
* => .*
\* => \* (i.e. no conversion.)
有人可以帮帮我吗?
答案 0 :(得分:4)
使用lookbehind。
String resultString = subjectString.replaceAll("(?<!\\\\)\\*", ".*");
说明:
"(?<!" + // Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind)
"\\\\" + // Match the character “\” literally
")" +
"\\*" // Match the character “*” literally
答案 1 :(得分:1)
可能没有捕获组,但这应该有效:
myString.replaceAll("\\*([^\\\\]|$)", "*.$1");