[HackerRank][Regex](java) Grouping and Capturing

728x90

 


 

■  Capturing & Non-Capturing Groups

https://www.hackerrank.com/challenges/capturing-non-capturing-groups/problem?isFullScreen=true 

Q.

You have a test String S.
Your task is to write a regex which will match S with the following condition:

*  S should have 3 or more consecutive repetitions of ok.

※  Parenthesis ( ) around a regular expression can group that part of regex together. This allows us to apply different quantifiers to that group.
These parenthesis also create a numbered capturing. It stores the part of string matched by the part of regex inside parentheses.
These numbered capturing can be used for backreferences. ( We shall learn about it later )
( https://learn.microsoft.com/en-us/dotnet/standard/base-types/quantifiers-in-regular-expressions?redirectedfrom=MSDN )

※  (?: ) can be used to create a non-capturing group. It is useful if we do not need the group to capture its match.

A.

(ok){3,}

 


 

■  Alternative Matching

https://www.hackerrank.com/challenges/alternative-matching/problem?isFullScreen=true 

Q.

Given a test string, s, write a RegEx that matches s under the following conditions:

*  s must start with Mr., Mrs., Ms., Dr. or Er..
*  The rest of the string must contain only one or more English alphabetic letters (upper and lowercase).

※  Alternations, denoted by the | character, match a single item out of several possible items separated by the vertical bar. When used inside a character class, it will match characters; when used inside a group, it will match entire expressions (i.e., everything to the left or everything to the right of the vertical bar). We must use parentheses to limit the use of alternations.
(ex) (Bob|Kevin|Stuart) will match either Bob or Kevin or Stuart.
(ex) ([a-f]|[A-F]) will match any of the following characters: a, b, c, d, e, f, A, B, C, D, E, or F.

A.

^(Mr|Mrs|Ms|Dr|Er)\.[a-zA-Z]+$

 


 

■  Matching Word Boundaries

https://www.hackerrank.com/challenges/matching-word-boundaries/problem?isFullScreen=true 

Q.

You have a test String S.
Your task is to write a regex which will match word starting with vowel (a,e,i,o, u, A, E, I , O or U).
The matched word can be of any length. The matched word should consist of letters (lowercase and uppercase both) only.
The matched word must start and end with a word boundary.

※  \b assert position at a word boundary.
Three different positions qualify for word boundaries :
► Before the first character in the string, if the first character is a word character.
► Between two characters in the string, where one is a word character and the other is not a word character.
► After the last character in the string, if the last character is a word character.

(ex) \bcat\b => A 'cat', acat

A.

\b[aeiouAEIOU][a-zA-Z]*\b

 


 

 

반응형