Question

A token can be like this {num} or {num:2} (2 being an arg)

I would like to achieve matching like this:

// no args
[0] = num

// args (anything after the colon and before the closing brace as one match is fine)
[0] = num
[1] = 2

I managed to match anything in the braces that was easy but my regex is too noob to get anything more complex than that! Thanks.

FYI I am using javascript and \{(.*?)\} matches all the contents within.

Was it helpful?

Solution

You could do something like this:

\{(.*?)(?::(.*?))?\}

And a test:

> '{foo:bar}'.match(/\{(.*?)(?::(.*?))?\}/)
["{foo:bar}", "foo", "bar"]
> '{foo}'.match(/\{(.*?)(?::(.*?))?\}/)
["{foo}", "foo", undefined]
  • (.*?) non-greedily matches the first group.
  • (?:...) is a non-capturing group. It's just like a regular capturing group, but it doesn't get captured.
  • :(.*?) captures the stuff after the colon.
  • ? makes that last group (which contains the colon and the second capturing group) optional.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top