我正在尝试提出一个正则表达式,它只能匹配字符串中没有特殊转义序列的字符.
例如,在字符串中Is ? stranded//?,我希望能够替换?未被另一个字符串转义的字符串,因此我可以得到以下结果:**Is Dave stranded?**
但对于我的生活,我一直无法找到方法.我只提出了吃掉所有可替换字符的正则表达式.
如何构造一个只匹配前面没有转义序列的字符的正则表达式?
使用负面的外观,这是他们的目的!
(?<!//)[\?]
制动它:
(
?<! #The negative look behind. It will check that the following slashes do not exist.
// #The slashes you are trying to avoid.
)
[\?] #Your special charactor list.
Run Code Online (Sandbox Code Playgroud)
只有在找不到//时,它才会在搜索的其余部分进行.
我认为在Java中它需要再次转义为字符串,例如:
Pattern p = Pattern.compile("(?<!//)[\\?]");
Run Code Online (Sandbox Code Playgroud)
试试这个 Java 代码:
str="Is ? stranded//?";
Pattern p = Pattern.compile("(?<!//)([?])");
m = p.matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1).replace("?", "Dave"));
}
m.appendTail(sb);
String s = sb.toString().replace("//", "");
System.out.println("Output: " + s);
Run Code Online (Sandbox Code Playgroud)
Output: Is Dave stranded?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4537 次 |
| 最近记录: |