Regex capturing group question

Hello I need help understanding why this doesn’t return what I expected:

Regex.Match("of 850 ",“of (\d+)”)

I expect it to return “850”, but instead it returns “of 850”, isn’t the () supposed to capture the digits only? how can I make this work using Regex, not other methods like split strings. thanks

grafik

1 Like

Hey @lynnsong986

Essentially your pattern is wrong :confused: You are matching ALL of the input string (“of 850”).
image

The second set of quotation marks (“of (\d+)”) is the ‘Regex pattern’. The brackets just create ‘groups’ within a Regex Pattern. Groups allow you to easily capture components of a bigger string like a year, month and date separately (see below)
Regex Pattern with Groups:
image
Results with Groups:
image

If you just need “850” as the result/output then update it to “\d+”. If you want it in group 1 then update the pattern to “(\d+)”.

I would highly recommend using the below template with an Assign activity:
system.Text.RegularExpressions.Regex.Match(INSERTxINPUTxSTRINGxVARIABLE, “INSERTxREGEXxPATTERN”).ToString

Template Explanation:

  • The italics is where you should place the input string variable.
  • The bold is where you should insert the Regex Pattern.
  • Note this will only match the first result only

Hopefully this helps you :blush:

Hi,

Another solution:

Can you try the following expression?

System.Text.RegularExpressions.Regex.Match("of 850 ","of (\d+)").Groups(1).Value

Regards,

3 Likes

Thank you all! would you please tell me what the grey and yellow color mean in this screenshot?

my bad, I forgot to use groups(1) to capture the digits, and Match returns the whole matched string including everything. Thank you so much again! I think they should allow multiple solutions here! If you don’t mind I still need to know what each color represents in the attached.

my guess:
Grey: part of all matched string
Yellow: capturing groups

Hi,

Probably, they are as the following.

Grey : Matched characters
Yellow: Characters of Capturing Group

Regards,

1 Like

just give the solution flag to post of your choice. For the others you can use the likes

2 Likes

@Yoichi Thank you for confirming that!

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.