String.replaceAll的正则表达式

时间:2011-11-17 08:54:54

标签: java regex string replaceall

我需要一个可以与String类的replaceAll方法一起使用的正则表达式,将*的所有实例替换为.*,除了尾随\ < / p>

即。转换将是

[any character]*[any character] => [any character].*[any character]
* => .*
\* => \* (i.e. no conversion.)

有人可以帮帮我吗?

2 个答案:

答案 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");