How to express ":" but not preceded by "\" in a Java regex?

How can I express "not preceded" in a Java regular expression? For example, I would like to search for ":", but only when it is not preceded by "\". How can i do this?

+7
java regex
source share
2 answers

Use negative lookbehind :

"(?<!\\\\):" 

The reason for the four backslashes:

  • The backslash is a special character in regular expressions, so you need the regular expression \\ to match a single backslash.
  • backslashes must be escaped in Java strings, so each of the above backslashes must be written as \\ , giving a total of four.

Code example:

 Pattern pattern = Pattern.compile("(?<!\\\\):"); Matcher matcher = pattern.matcher("foo\\:x bar:y"); if (matcher.find()) { System.out.println(matcher.start()); } 

Output:

 10 
+14
source share

Have you tried using the character class with the padding operator?

  String s1 = "foo : bar"; String s2 = "foo \\: bar"; Pattern p = Pattern.compile("[^\\\\]:"); Matcher m = p.matcher(s1); if(m.find()) { System.out.println(m.group()); } m = p.matcher(s2); if(m.find()) { System.out.println(m.group()); } 
+1
source share

All Articles