Regular expressions 4. Special constructs with parentheses

Some special constructs exist with parentheses.

(?:regex) is a grouping-only construct.
They exist merely for efficiency reasons and facilitate grouping.
(?=regex) is a positive look-ahead.
A match of the regular expression contained in the positive look-ahead construct is attempted. If the match succeeds, control is passed to the regex following this construct and the text consumed by this look-ahead construct is first unmatched.
(?!regex) is a negative look-ahead.
Functions like a positive look-ahead, only the regex must not match.
Example: "abc(?!.*abc.*)" searches for the last occurrence of "abc" in a string.
(?iregex) is a case insensitive regex.
(?Iregex) is a case sensitive regex.
Default a regex is case sensitive.
    Example: "(?iaa)" matches "aa", "aA", "Aa" and "AA".
(?nregex) matches newlines.
(?Nregex) doesn't match newlines.

All the constructs above do not capture text and cannot be referenced, i.e., the parentheses are not counted. However, you can make them capture text by surrounding them with ordinary parentheses.

Links to this page

© djmw, July 10, 2001