Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regular expression non capture group

Tags:

regex

ruby

I'm trying to grab id number from the string, say

id/number/2000GXZ2/ref=sr

using

(?:id\/number\/)([a-zA-Z0-9]{8})

for some reason non capture group is not worked, giving me:

id/number/2000GXZ2
like image 385
AKarpun Avatar asked Feb 17 '16 16:02

AKarpun


People also ask

What is non-capturing group in regular expression?

Overview. Non-capturing groups are important constructs within Java Regular Expressions. They create a sub-pattern that functions as a single unit but does not save the matched character sequence. In this tutorial, we'll explore how to use non-capturing groups in Java Regular Expressions.

What do you put at the start of a group to make it non-capturing?

Sometimes you want to use parentheses to group parts of an expression together, but you don't want the group to capture anything from the substring it matches. To do this use (?: and ) to enclose the group.

What is regex capture group?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .


1 Answers

As mentioned by others, non-capturing groups still count towards the overall match. If you don't want that part in your match use a lookbehind. Rubular example

(?<=id\/number\/)([a-zA-Z0-9]{8})

(?<=pat) - Positive lookbehind assertion: ensures that the preceding characters match pat, but doesn't include those characters in the matched text

Ruby Doc Regexp

Also, the capture group around the id number is unnecessary in this case.

like image 95
jacob.mccrumb Avatar answered Sep 29 '22 20:09

jacob.mccrumb