norbre norbre - 4 months ago 6
Javascript Question

Regex - find all matches in a string with conditions (javascript)

Please help me, I am a regex beginner and I didn't find a soluton.

I have a string like this:

(name:"apple",color:"red"),(name:"orange",color:"orange"),(name:"berry",color:"red",color:"black")


I would like to find all matches (name) with a "color" condition.
Example if:



  • color is RED, the result is: APPLE and BERRY

  • color is ORANGE, the result is: ORANGE

  • color is BLACK, the result is: BERRY




This is the way I tried:
This lists all of names (apple, orange, berry):

name:"(.*?)"


This find a match of two "condition":

color:"red"


But if I try to combine like this..

name:"(.*?)color:"red"


.. the result is 'apple' and 'orange",color:"orange"),(name:"berry",'

thank you

Answer

Here is a regex that finds all groups that contain the color, but the name must come before the color

\(name:"([^"]*)"[^\)]*color:"red"[^\)]*\)

http://refiddle.com/refiddles/57a34ab575622d6f2c130000

for the string:

(name:"apple",color:"red"),(name:"orange",color:"orange"),(name:"berry",color:"red",color:"black")

you'll get two matches and the name is in group #1 of each match