我正在尝试解析以下字符串格式:
<id>:<name>[,<name>]*
举个例子,考虑 123:test,south-west,best,rest_well
.
我编写了以下正则表达式:
/(\d+):([a-zA-Z0-9_\-]+)(?:,([a-zA-Z0-9_\-]+))*/
我的假设是(?:,([a-zA-Z0-9_\-]+))
将捕获可选的附加名称(south-west、best 和rest_well)。但是,它仅捕获姓氏“rest_well”。
打印出的匹配:
'123:test,south-west,best,rest_well'.match(/(\d+):([a-zA-Z0-9_\-]+)(?:,([a-zA-Z0-9_\-]+))*/);
> ["123:test,south-west,best,rest_well", "123", "test", "rest_well"]
我所期待的:
> ["123:test,south-west,best,rest_well", "123", "test", "south-west", "best", "rest_well"]
我相信其他语言实际上会累积匹配的组,但不知何故这失败了。也许我遗漏了一个小细节。如有任何帮助,我们将不胜感激!
最佳答案
听起来您只想用 :
或 ,
分割字符串。这行得通吗?
var str = "123:test,south-west,best,rest_well";
var res = str.split(/:|,/);
输出
["123", "test", "south-west", "best", "rest_well"]
关于JavaScript RegEx 集团,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24332322/