PlayMa256
PlayMa256

Reputation: 6841

Capture groups inside string using regular expression

i dont know much about regular expressions and from what i'v learned i cant solve my entire problem.

I have this String:

04 credits between subjects of block 02

I'm only sure i will have [00-99] on the beggining and at end.

I wanna capture the beggining and the end IF the middle has "credits between", the system can have other formats as input, so i wanna be sure that these fields captured will go from the correct pattern.

This is what i'v tried to do:

(\w\w) ^credits between$.+ (\w\w)

I'm using the Regexr website to see what i'm doing, but no success.

Upvotes: 1

Views: 47

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

You may use the following regex:

^(\d{2})\b.*credits between.*\b(\d{2})$

See regex demo

It will match and capture 2 digits at the beginning and end if the string itself contains credits between. Note that newlines can be supported with [\s\S] instead of ..

The word boundaries \b just make the engine match the digits followed by a non-word character (you may remove it if that is not expected behavior). Then, you'd need to use ^(\d{2})\b.*credits between.*?(\d{2})$ with the lazy matching .*? at the end.

If the number of digits in the numbers at both ends can vary, just use

^(\d+).*credits between.*?(\d+)$

See another demo

Upvotes: 2

Related Questions