[英]Regular expression to match unescaped special characters only
我正在尝试提出一个正则表达式,它只能匹配字符串中没有特殊转义序列的字符。
例如,在字符串中Is ? stranded//?
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.
只有在找不到//时,它才会在搜索的其余部分进行。
我认为在Java中它需要再次转义为字符串,例如:
Pattern p = Pattern.compile("(?<!//)[\\?]");
试试这个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);
Output: Is Dave stranded?
我正在考虑这个,并有第二个更简单的解决方案,避免正则表达式。 其他答案可能更好,但我想我可能会发布它。
String input = "Is ? stranded//?";
String output = input
.replace("//?", "a717efbc-84a9-46bf-b1be-8a9fb714fce8")
.replace("?", "Dave")
.replace("a717efbc-84a9-46bf-b1be-8a9fb714fce8", "?");
只是保护“//?” 用一些独特的东西(如guid)替换它。 然后你知道任何剩下的问号都是合理的游戏。
使用分组。 这是一个例子:
import java.util.regex.*;
class Test {
public static void main(String[] args) {
Pattern p = Pattern.compile("([^/][^/])(\\?)");
String s = "Is ? stranded//?";
Matcher m = p.matcher(s);
if (m.matches)
s = m.replaceAll("$1XXX").replace("//", "");
System.out.println(s + " -> " + s);
}
}
输出:
$ java Test
Is ? stranded//? -> Is XXX stranded?
在这个例子中,我是:
编辑使用if (m.matches)
确保正确处理不匹配的字符串。
这只是一个快速而肮脏的例子。 显然,你需要充实它,使其更加强大。 但它得到了一般的想法。
匹配除转义序列之外的一组字符,然后是正则表达式特殊字符。 您可以使用倒置字符类( [^/]
)作为第一位。 特殊情况下,字符串前面有一个未转义的正则表达式字符。
尝试匹配:
(^|(^.)|(.[^/])|([^/].))[special characters list]
String aString = "Is ? stranded//?";
String regex = "(?<!//)[^a-z^A-Z^\\s^/]";
System.out.println(aString.replaceAll(regex, "Dave"));
正则表达式的一部分[^az^AZ^\\\\s^/]
匹配非字母数字,空格或非正斜杠字符。
(?<!//)
部分做了负面的观察 - 请参阅docco以获取更多信息
这给出了输出Is Dave stranded//?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.