【问题标题】:Regular expression for String.replaceAllString.replaceAll 的正则表达式
【发布时间】:2023-03-10 02:50:02
【问题描述】:
我需要一个可以与 String 类的 replaceAll 方法一起使用的正则表达式,以将 * 的所有实例替换为 .*,除了结尾有 \ 的实例之外
即转换将是
[any character]*[any character] => [any character].*[any character]
* => .*
\* => \* (i.e. no conversion.)
有人可以帮帮我吗?
【问题讨论】:
标签:
java
regex
string
replaceall
【解决方案1】:
使用后视。
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
【解决方案2】:
可能没有捕获组,但这应该可行:
myString.replaceAll("\\*([^\\\\]|$)", "*.$1");