javascript regex how to match only parts in a list with mandatory prefix

Viewed 39

I want to match ": red", ": 10", ": [special]" only if category present before (I want to use replace function to get rid of them afterwards)

category fruit(color: red, size: 10, others: [special])

I have this regex for above

(((:\s*[\w\[\]]+)(?=[,\)]))+)

except for category, I can't seem to be able to use lookbehind for that.

2 Answers

If we take the the following input verbatim:

Figure I - Input String

category fruit(color: red, size: 10, others: [special])

Using a positive lookbehind to match literal : red, : 10, and : [special]:

Figure II

/(?<=category[\S\s]+?)(:\s?red|:\s?10|:\s?\[special\])/g

Figure III

Segment Description
(?<=category[\S\s]+?) Match, but do not consume, literal "categorey", anything in between if it proceeds...
(:\s?red|:\s?10|:\s?\[special\]) ...literal colon, zero to one space, literal "read" OR literal colon, zero to one space, literal "10" OR literal colon, zero to one space, literal "[special]"

See Regex101

Jeffery Flynt commented that it isn't syntactically correct, I'd have to agree

If you want to match word characters before the colon and either word characters after the colon or from[...], and the values have to be between parenthesis, then you might also use:

(?<=\bcategory\s[^()]*\([^()]*\w):\s*(?:\w+|\[[^\[\]]*\])(?=[^()]*\))

Explanation

  • (?<= Positive lookbehind assertion, check what is to the left is:
    • \bcategory\s+[^()]* Match the word category, followed by whitespace chars and optionally any char except parenthesis
    • \([^()]*\w Match ( and again any char except parenthesis followed by a word char
  • ) Close the lookbehind
  • :\s* Match : and optional whitespace chars
  • (?:\w+|\[[^\[\]]*\]) Match either 1+ word chars, or match from [...]
  • (?=[^()]*\)) Positive lookahead, assert ) to the right

Regex demo

Related