HackerRank - Regex - Assertions

© HackerRank

Positive Lookahead

regex_1(?=regex_2)

The positive lookahead (?=) asserts regex_1 to be immediately followed by regex_2. The lookahead is excluded from the match. It does not return matches of regex_2. The lookahead only asserts whether a match is possible or not.

For Example

1
c(?=o)

is matched with chocolate

Task

gooooo!

1
o(?=oo)

Negative Lookahead

regex_1(?!regex_2)

The negative lookahead (?!) asserts regex_1 not to be immediately followed by regex_2. Lookahead is excluded from the match (do not consume matches of regex_2), but only assert whether a match is possible or not.

For Example

1
c(?!o)

is matched with chocolate

Task

If S =goooo, then regex should match goooo. Because the first g is not follwed by g and the last o is not followed by o.

gooooo

1
(\S)(?!\1)

Positive Lookbehind

(?<=regex_2)regex_1

The positive lookbehind (?<=) asserts regex_1 to be immediately preceded by regex_2. Lookbehind is excluded from the match (do not consume matches of regex_2), but only assert whether a match is possible or not.

For Example

1
(?<=[a-z])[aeiou]

is matched with helo

Task

123Go!

1
(?<=[13579])\d

Negative Lookbehind

(?<!regex_2)regex_1

The negative lookbehind (?<!) asserts regex_1 not to be immediately preceded by regex_2. Lookbehind is excluded from the match (do not consume matches of regex_2), but only assert whether a match is possible or not.

For Example

1
(?<![a-z])[aeiou]

is matched with helo

Task

1o1s

1
(?<![aeiuoAEIOU]).

Resources

Regex - Subdomains - Assertions