1

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?

Alan Moore
  • 71,299
  • 12
  • 93
  • 154
sylvain
  • 246
  • 2
  • 5

3 Answers3

0

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
  • 11,829
  • 14
  • 65
  • 101
0

Here's the regex I came up with:

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

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

Jason Thompson
  • 4,464
  • 5
  • 47
  • 73
  • 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 Aug 13 '10 at 03:36
0

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
  • 32,638
  • 9
  • 79
  • 112