1

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?

FrozenDroid
  • 166
  • 13
  • check this out http://stackoverflow.com/questions/7124778/how-to-match-anything-up-until-this-sequence-of-characters-in-a-regular-expres – Parth Akbari May 07 '15 at 09:02
  • That's not what I need, because it's not an exact sequence of characters. It could also be "met {whatever} {whatever}". – FrozenDroid May 07 '15 at 09:04

1 Answers1

1
(?: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

vks
  • 67,027
  • 10
  • 91
  • 124
  • If I try that, I get: `0 => string 'met ' (length=4)` – FrozenDroid May 07 '15 at 09:02
  • Is there no other way? Can you like, reference to a pattern or is there no such thing in regexes? – FrozenDroid May 07 '15 at 09:08
  • 1
    I did use the new code, and it does work, but the problem is that I will be creating quiet a few more patterns, and if I have to put them in the lookahead it could get a mess. – FrozenDroid May 07 '15 at 09:11
  • @FrozenDroid you can use `met [a-zA-Z ]*` if you want to capture only sentence..........if there are more patterns you can always club them together in `lookahead` with `|`.We need some solid pattern for `met ...` to make it stop or else `lookahead` :) – vks May 07 '15 at 09:14
  • Yeah the problem here is, there isn't really a "pattern", that's what makes it really difficult for me :P I guess a lookahead is the only real solution here. Thanks! – FrozenDroid May 07 '15 at 09:18
  • Actually, it's not working. "met interne weerstand" doesn't have to match only if there's a match after it. I need it so you can also type "led met interne weerstand". – FrozenDroid May 07 '15 at 09:27
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/77169/discussion-between-frozendroid-and-vks). – FrozenDroid May 07 '15 at 09:31