Java Regexp Lookahead Lookbehind

java

http://www.ocpsoft.org/opensource/guide-to-regular-expressions-in-java-part-2/

Does look-ahead and look-behind affect group numbering?

No. They do not capture values; therefore, using these constructs, no values will be stored for later retrieval, and they do not affect group numbering. See http://www.ocpsoft.org/opensource/guide-to-regular-expressions-in-java-part-2/

What are common look-ahead and look-behind constructs?

(?:X)             X, as a non-capturing group
(?=X)             X, via zero-width positive look-ahead
(?!X)             X, via zero-width negative look-ahead
(?<=X)             X, via zero-width positive look-behind
(?<!X)             X, via zero-width negative look-behind
(?<X)             X, as an independent, non-capturing group

What is negative lookahead?

Negative Lookahead provides the possibility to exclude a pattern. With this you can say that a string should not be followed by another string. Negative Lookaheads are defined via (?!pattern). For example:

a(?!b)

will match "a" if "a" is not followed by "b".

We can use a negative look-ahead to ensure that there are no occurrences.

How to do a zero-width positive look-ahead?

(?=X)

How to do a zero-width negative look-ahead?

(?!X)

How to do a zero-width positive look-behind?

(?<=X)

How to do a zero-width negative look-behind?

(?<!X)

Examples of look-ahead and look-behind?

String ssn = "...";
if (ssn.matches("^(?=.*[0-9].*[0-9])[0-9a-zA-Z]{8,12}$")) {
}
^                match the beginning of the line
(?=.*[0-9].*[0-9])         a look-ahead expression, requires 2 digits to be present
.*                match n characters, where n >= 0
[0-9]                match a digit from 0 to 9
[0-9a-zA-Z]            match any numbers or letters
{8,12}                match 8 to 12 of whatever is specified by the last group
$                match the end of the line
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License