Jump to content

Advanced Regex problem. First vs last match!


Anidazen

Recommended Posts

Hello.

When trying to run regular expressions, it seems sometimes the expression doesn't want to pick the first instance as it should.

Example would be: "/blah.*?([0-9]*)/is" on the following:
blah 25 blahblah blah 62 blah blah blahblah 33

In this example, it would return either 62 or 33, but not 25 - which would match if there were nothing after it. This is incredibly frustrating and is ofc. breaking my script's use. How can I fix this? Why does this happen!



Thanks in advance.
Link to comment
Share on other sites

I'm surprised that expression returned any numbers at all for that example.

The reason it's not doing what you want is because of the asterisk after the number class ([0-9][color=red]*[/color]).  What your entire expression means is "find 'blah' followed by zero or more of anything without being greedy, followed by zero or more numbers."  But both of those "zero or more" characters match at the zero-length atom(?) just beyond "blah".  To the regular expression engine it's as if there were an invisible character between the "h" in "blah" and the space following it.  This is analagous to the word boundry class (\b) where a match occurs between a word character and a non-word character.

Effigy's suggestion will work fine for you, unless you require that there be a space between "blah" and the trailing number, in which case you'd need to use "\s+" instead of "\s*".
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.