qwertymk
qwertymk

Reputation: 35256

regex ignore capturing group inside capturing group

I'm trying to capture a group but at the same time ignore a sub group but need the subgroup to be true to capture it. For example:

/^(?:\s*)([abc])?(?:\s*)((?:d){1}[ef]*)(.*)/.exec(' a deee ghi')
// is equal to                [" a deee ghi", "a", "deee", " ghi"]
// but I really want equal to [" a deee ghi", "a", "eee", " ghi"]

// and I want this to fail:
/^(?:\s*)([abc])?(?:\s*)((?:d){1}[ef]*)(.*)/.exec(' a eee ghi')
//                            [" a eee ghi", "a", "", "eee ghi"]

I'm trying to ignore the 'd' in the capturing group but only want it captured if there's a 'd' before any 'e's of 'f's in the third group

How would I do this?

EDIT:

To clairify, I want the third group to be filled only if there's a 'd' in the string there. else -> don't capture the 'e's or 'f's

Upvotes: 1

Views: 2766

Answers (1)

ruakh
ruakh

Reputation: 183211

If I understand you correctly: if the d is there, then the capture-group should be eee, but if the d is not there, then the capture-group should be blank or null. Is that correct? If so, you can write:

/^(?:\s*)([abc])?(?:\s*)(?:d([ef]*)|[ef]*)(.*)/.exec(' a deee ghi')

to match ([ef]*) when d is present, and [ef]* when it is not.

Upvotes: 3

Related Questions