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?
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.
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.
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.
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 .
Use a negative lookbehind:
"(?<!\\\\):"
The reason for the four backslashes is:
\\
to match a single backslash.\\
, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With