Skip to content
Advertisement

Regular expression to match unescaped special characters only

I’m trying to come up with a regular expression that can match only characters not preceded by a special escape sequence in a string.

For instance, in the string Is ? stranded//? , I want to be able to replace the ? which hasn’t been escaped with another string, so I can have this result : **Is Dave stranded?**

But for the life of me I have not been able to figure out a way. I have only come up with regular expressions that eat all the replaceable characters.

How do you construct a regular expression that matches only characters not preceded by an escape sequence?

Advertisement

Answer

Try this Java code:

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

Output: Is Dave stranded?
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement