views:

32

answers:

3

Been trying to come up with a regex in JS that could split user input like :

"Hi{user,10,default} {foo,10,bar} Hello"

into:

["Hi","{user,10,default} ","{foo,10,bar} ","Hello"]

So far i achieved to split these strings with ({.+?,(?:.+?){2}})|([\w\d\s]+) but the second capturing group is too exclusive, as I want every character to be matched in this group. Tried (.+?) but of course it fails...

Ideas fellow regex gurus?

A: 

Use this:

"Hi{user,10,default} {foo,10,bar} Hello".split(/(\{.*?\})/)

And you will get this

["Hi", "{user,10,default}", " ", "{foo,10,bar}", " Hello"]

Note: {.*?}. The question mark here ('?') stops at fist match of '}'.

Topera
A: 

Here's the regex I came up with:

(:?[^\{])+|(:?\{.+?\})

Like the one above, it includes that space as a match.

Jason Thompson
It's almost what I am looking for, but I want to enforce the 3 args rule between the curly braces, i.e. if there is `"Hi {simple} {user,10,default}"`, I am expecting `["Hi {simple}", {user,10,default}"]` as a result.
sylvain
A: 

Beeing no JavaScript expert, I would suggest the following:

  • get all positive matches using ({[^},]*,[^},]*,[^},]*?})
  • remove all positive matches from the original string
  • split up the remaining string

Allthough, this might get tricky if you need the resulting values in order.

phimuemue