[英]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 : 一直试图在JS中提出一个正则表达式,它可能会分割用户输入,例如:
"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. 到目前为止,我实现了用
({.+?,(?:.+?){2}})|([\\w\\d\\s]+)
分割这些字符串,但是第二个捕获组太排斥了,因为我希望该组中的每个字符都匹配。 Tried (.+?)
but of course it fails... 尝试过
(.+?)
但当然失败了...
Ideas fellow regex gurus? 想法正则表达式大师?
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 '}'. 问号('?')停在第一笔匹配的'}'处。
Here's the regex I came up with: 这是我想出的正则表达式:
(:?[^\{])+|(:?\{.+?\})
Like the one above, it includes that space as a match. 像上面的那个一样,它包含该空间作为匹配项。
Beeing no JavaScript expert, I would suggest the following: 没有JavaScript专家,我建议以下几点:
({[^},]*,[^},]*,[^},]*?})
({[^},]*,[^},]*,[^},]*?})
获得所有正匹配项 Allthough, this might get tricky if you need the resulting values in order. 尽管如此,如果您需要按顺序排列结果值,这可能会变得棘手。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.