Ambrish
Ambrish

Reputation: 3677

Regex group re-structuring

I have input data as following as:

AB
AB_Test
AB_Test123

Expected output:

AB
AB_Test

I have regex which matches:

    ([A-Z]{2})(_([a-zA-Z]*))?

Regular expression visualization

Debuggex Demo

So from above regex, I get the strings in $1 & $3. I want to modify the regex such that the strings will be in $1 & $2 (omit group 2 from above regex).

Now I want to process the matched strings using the group. That is why I want it to be in sequence.

Is there are way by which we can change the above regex?

Upvotes: 1

Views: 54

Answers (2)

dawg
dawg

Reputation: 104092

If you are trying to eliminate the strings that have digits, use a negative lookahead assertion:

^([A-Z]{2})(?!.*\d.*)(?:_([A-Za-z]*))?

Demo

Or add anchors on both ends of the string:

^([A-Z]{2})(?:_([A-Za-z]*))?$

Demo 2

If you use anchors, you will need to use the m flag if you have a multiline target.

Upvotes: 1

Brian Stephens
Brian Stephens

Reputation: 5271

You need to use a non-capturing group for the one you don't want:

^([A-Z]{2})(?:_([a-zA-Z]*))?$

EDIT: I also added beginning and ending anchors because it seems that you want to match the line only if the characters after the underscore are all letters.

Upvotes: 1

Related Questions