2

I have a text:

Wheels – F/R_ Schwalbe TABLE TOP/Schwalbe Black Jack 26x2.2

And regex to parse wheels size from that string:

/.*Wheels.*(\d*)x/

But it does not work. Besides, when i'm removing asterisk from regex, i'm getting number 6 as group match.

3
  • 1
    .*Wheels.*?(\d*)x Commented Feb 15, 2017 at 17:42
  • @PavneetSingh , working, but could you please explain where was my mistake and format that as an answer, so i can accept it. Commented Feb 15, 2017 at 17:44
  • Just to clarify, you want to select 'Wheels' from the string and nothing else? Commented Feb 15, 2017 at 17:45

2 Answers 2

4

You need to make your .* before the digits lazy instead of greedy:

/.*Wheels.*?(\d*)x/

The .* will greedily consume everything up to the x, leaving nothing for the following \d*. Since * can validly match zero characters, an empty match for \d* is not an incorrect result.

By adding a ? to make a lazy .*? expression, it will try match as few characters as possible, allowing the following \d* to match all the numbers before the x.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the explanation!
Wow great explanation, I finally understand what lazy means in regex!
2

You need to make your regex non-greedy because .* will consume your digits and \d* mean zero or no match

.*Wheels.*?(\d*)x 

.*? mean match as many characters as few time as possible to stop .* to consume your digits

Follow this Demo for example


Alternately you can make it more efficient if there are no digits after Wheel and your desired values with following regex

.*Wheels[^\d]*(\d*)x

where [^\d]* mean matches anything except digits

2 Comments

Thank you for the explanation!
@Src i am glad that i could help , happy coding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.