Question: how to get the "Matches" function / RegEx Expression to work

I want to get a value from a text file and Output it to a variable. I got this to work to a certain extend but don’t know how to make it perfect. So heres the issue.

In the text file theres always the same patern: “(P******)”, the stars being numbers. I want to extract these numbers, but only when theres a P infront of it and between brackets. so… I came up with the following RegEx Expression: “\ (P(\d{6})\ )” This extracts exactly what I need. but I don’t want the brackets and P in the Variable. How can I solve this?

In short: I want 6 numbers when theres a P in front of it AND when its between brackets.

I tried figuring this out for a while now. Basic tutorials dont seem to cover this / I dont understand how it works.

@Peter_Peter Use regex like This

To my knowledge this extracts any 6 number combination, correct me if im wrong?
The text file I want to extract from has lots of numbers, so I want to only extract when theres a P in front of it and inbetween brackets

There are a couple of ways to do this.

What I would suggest is using the group 1 match instead of the entire match. In other words, same regex pattern, but what you actually use for your later processing is the subgroup 1

1 Like

alright thanks, I think thats what im looking for indeed. The numbers are in subgroup 1 I think because its inbetween brackets. Currently im using the For Each function: (ForEach item, item.ToString) This outputs the entire match though

I found my answer in this comment. Thanks

When you do Regex.Matches you basically have two levels of results:

  • The match collection. This just gives you the entire matched string, the number of times it’s been matched in the text.
  • For every match, you also have captured groups (In this case, you can only have two captured groups, \0 and \1). The one you’re looking for is \1 (since \0 is just the entire match)
1 Like

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