FrozenDroid
FrozenDroid

Reputation: 166

Regex match until another match

I am trying to create a regex that parses the properties of a product, for example:
"led met interne weerstand 1/4w 1k" would parse into:

[0] met interne weerstand  
[1] 1/4w  
[2] 1k

So far, I have this regex:
/(?:met .*)|(?:(?:\d+\/)?\d+\w ?)|(?:\d+ ?in ?\d+)/

And I'm trying to match 1/4w 1/4s 1/4w 1/4d 3 in 1 1% led met interne weerstand 1/4w against it.

It doesn't work the way I want it to work:

array (size=6)
  0 => 
    array (size=1)
      0 => string '1/4w ' (length=5)
  1 => 
    array (size=1)
      0 => string '1/4s ' (length=5)
  2 => 
    array (size=1)
      0 => string '1/4w ' (length=5)
  3 => 
    array (size=1)
      0 => string '1/4d ' (length=5)
  4 => 
    array (size=1)
      0 => string '3 in 1' (length=6)
  5 => 
    array (size=1)
      0 => string 'met interne weerstand 1/4w' (length=26)

Met interne weerstand is also matching 1/4w, but I want 1/4w to be a seperate match.
How do I do this?

Upvotes: 1

Views: 168

Answers (1)

vks
vks

Reputation: 67988

(?:met .*?(?=(?:(?:\d+\/)?\d+\w ?)|$))|(?:(?:\d+\/)?\d+\w ?)|(?:\d+ ?in ?\d+)

        ^^

A non greedy approach would work for you with a lookahead.See demo.

https://regex101.com/r/bN8dL3/9

Upvotes: 1

Related Questions