Regex matches, dynamic groups

I have a bunch of regex patterns in a control table which will be like “Incident number: (\d{1,10})”

However, the next activity I have is to Assign “value_IncidentNumber = IncidentNumber_matches(0).group(1).tostring”

The problem is that if I use an OR in my regex pattern, the group number changes. So for some transactions this is usually fine (as it usually returns in Group 1) but there is one provider with a regex pattern that contains OR so the value I need to extract is in Group 2. How can I make this so that it always returns perhaps the last found group in the matches?

ie. There is one regex pattern for one provider which has a variant, so I want to put an OR in regex. Example, “Incident number: (\d{1,10})|Job number: (\d{1,10})”
Where the number may be either proceeding “Incident number:” OR “Job number:”

@Jon_G
As an alternate - taking the last group:
Matches(0).Groups.Cast(Of Group).Last().toString

2 Likes

Hey Jon - I think you can name your groups using (?<name of group> regexpattern ), might be worth a try but sounds like you’ve solved it.

1 Like

Thanks so much! This worked way better (ppr’s response).

To elaborate, my solution only worked in one scenario where the count (2) worked fine for “match(0).groups(2)” to return the 2nd group. The issue I found next was I had a scenario where I had multiple matches but only 1 group each. ie. Match(0).Groups(1) plus Match(1).Groups(1)… anytime I tried to use matches.count it gave me “2” which wasn’t helping here as it (match(0).groups(2)) would just return null value. So your above solution was the best for my workflow. I first check to ensure count of matches>0, and then I just use match(0).last group using your method.

1 Like

Hey ppr, still having some issues with this.

Basically, I get the following.

TEXT A = Incident number 12345678
TEXT B = Job number 12345678
TEXT C = Job number 12345678

Regex expression =
Incident number: (\d{1,10})|Job number: (\d{1,10})

It seems now TEXT B + C is now working, but TEXT A returns null value.
For TEXT A,
IncidentNo_matches(0).Groups(1).ToString = 12345678
IncidentNo_matches(0).Groups.Cast(Of Group).Last().ToString = null

Any ideas how I can tweak this so that it can return the Incident Number value in all cases of the OR expression?

have a look here:
grafik

(Incident|Job)( number)(:?) (\d{1,10})

check the right requirement related to the : in your scenario

1 Like

You’re a champion! This works now. So my “number” is always the last catching group now, which also means the initial solution of Groups.Cast(Of Group).Last() now works with this too! :slight_smile:

Thanks so much

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