CodingUnderDuress
CodingUnderDuress

Reputation: 103

Trouble with non-capturing groups in regular expression

I'm attempting to capture the 6 digit number in the following:

ObjectID: !nrtdms:0:!session:slonwswtest1:!database:TEST:!folder:ordinary,486150:

I tried the following regex:

\d+(?::$)

attempting to use a non-capturing group to strip the colon out of the returned match, but it returns the colon as in:

486150:

Any ideas what I'm doing wrong?

Upvotes: 3

Views: 74

Answers (4)

Rohit Jain
Rohit Jain

Reputation: 213371

Probably your regex tool is returning the complete match since you don't have any capture group there. Try to enclose the \d+ in a capture group, and find the way to get capture group 1 in your regex tool.

Alternatively, you can also use positive look-ahead:

\d+(?=:$)

And given that you want to capture 6 digits, you can make that explicit:

\d{6}

Upvotes: 2

arshajii
arshajii

Reputation: 129577

You want a positive lookahead:

\d+(?=:$)

A non-capturing group is simply a group that cannot be accessed via a backreference; they still are part of the match, nonetheless.

Alternatively, you can use

(\d+):$

and obtain the 1st match group.

Upvotes: 3

Bergi
Bergi

Reputation: 665380

Non-capturing groups are groups that will not create a capture (to be used in backreferences or extracted from the match result). Nonetheless they will match the expression.

What you're looking for is lookahead - to test the expression but exclude it from the match:

\d+(?=:$)

Upvotes: 2

iruvar
iruvar

Reputation: 23394

You should use a positive lookahead rather than a non-capturing group

\d+(?=:$)

Upvotes: 2

Related Questions