Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I express ":" but not preceded by "\" in a Java regular expression?

Tags:

java

regex

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

like image 814
jjujuma Avatar asked Apr 25 '10 20:04

jjujuma


People also ask

How do you do except in regular expressions?

How do you ignore something in regex? To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

What does \\ mean in Java regex?

Backslashes in Java. The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.

How do you write a negation in regex?

Similarly, the negation variant of the character class is defined as "[^ ]" (with ^ within the square braces), it matches a single character which is not in the specified or set of possible characters. For example the regular expression [^abc] matches a single character except a or, b or, c.

What is the difference between \b and \b in regular expression?

Using regex \B-\B matches - between the word color - coded . Using \b-\b on the other hand matches the - in nine-digit and pass-key .


1 Answers

Use a negative lookbehind:

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

The reason for the four backslashes is:

  • 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.

Example code:

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

Output:

10
like image 138
Mark Byers Avatar answered Sep 19 '22 07:09

Mark Byers