开发者

Match a specific sequence or everything else with regex

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...开发者_如何学JAVA

Ideas fellow regex gurus?


Here's the regex I came up with:

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

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


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 '}'.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜