[HackerRank][Regex](java) Assertions

728x90

 


 

■  Positive Lookahead

https://www.hackerrank.com/challenges/positive-lookahead/problem?isFullScreen=true 

Q.

You have a test string S.
Write a regex that can match all occurrences of o followed immediately by oo in S.

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

(ex)
c(?=o) => cho'c'olate

A.

o(?=oo)

 


 

■  Negative Lookahead

https://www.hackerrank.com/challenges/negative-lookahead/problem?isFullScreen=true 

Q.

You have a test string S.
Write a regex which can match all characters which are not immediately followed by that same character.

(ex)
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.

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

(ex)
c(?!o) => 'c'hocolate

A.

(.)(?!\1)

 


 

■  Positive Lookbehind

https://www.hackerrank.com/challenges/positive-lookbehind/problem?isFullScreen=true 

Q.

You have a test String S.
Write a regex which can match all the occurences of digit which are immediately preceded by odd digit.

※  (?<=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
( JavaScript do not support lookbehind. )

(ex)
(?<=[a-z])[aeiou] => h'e'1o

A.

(?<=[13579])\d

 


 

■  Negative Lookbehind

https://www.hackerrank.com/challenges/negative-lookbehind/problem?isFullScreen=true 

Q.

You have a test String S.
Write a regex which can match all the occurences of characters which are not immediately preceded by vowels (a, e, i, u, o, A, E, I, O, U).

※  (?<!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.

(ex)
(?<![a-z])[aeiou] => he1'o'

A.

(?<![aeiouAEIOU]).

 


 

 

반응형