Reputation: 2535
How can I capture all parameter on sample string using Regex? I tried to use (\@\w+|\w+) pattern on https://regex101.com/ but it returns all words on sample string which is not what I expect.
.selector(@background, height, font "font-family, font family", @width : 10px, "red");
expected output should capture 5 parameters:
1. @background
2. height
3. font "font-family, font family"
4. @width : 10px
5. "red"
I'm having difficulties on combining regular expression and it took me an hour to figure it out that is why I decide to ask for a help.
Upvotes: 3
Views: 777
Reputation: 4966
Here is a all-in-one regex:
/(?<=[,\(])(?:\s*)([^,"]*(?<dq>")?(?(dq)[^"]+"[^\(\),]*))(?:\s*)/g
Explanation:
(?<=[,\(])
(?:\s*)
outside the caputring group (nicer).See on https://regex101.com/r/pC9fB6/1 the results.
Note: dystroy points out in a comment behind that lookbehind assertion is not supported by all regex engines (e.g. JavaScript). A possible solution is to put the character class [,\(]
of the lookbehind assertion inside the non-capturing group of whitespace: (?:[,\(]\s*)
. The result is almost the same, the numbered captured matches are exactly the same.
Upvotes: 0
Reputation: 67968
^.*?\(|,(?=(?:[^"]*"[^"]*")*[^"]*$)|\).*$
You can split by this and remove empty string
from the result.See demo.
https://regex101.com/r/nD5jY4/6
Upvotes: 0
Reputation: 382170
First, I would extract the interesting part between the parenthesis, then I would read the internal parameters:
var args = str.match(/\(([^\)]+)\)/)[1].match(/[^,"]+("[^"]+")*/g)
Result:
The idea of the second part ([^,"]+("[^"]+")*
) is to explicitly include parts between quotes.
Upvotes: 2