【问题标题】:JavaScript RegEx group conglomeration [duplicate]JavaScript RegEx 集团集团 [重复]
【发布时间】:2014-08-11 12:14:10
【问题描述】:

我正在尝试解析以下字符串格式:

<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"]

我相信其他语言实际上会积累匹配的组,但不知何故这失败了。也许我错过了一个小细节。任何帮助表示赞赏!

【问题讨论】:

  • 是的,看起来是这样。太糟糕了,但我可以用不同的方式来写。只是希望有一个漂亮的解决方案;)
  • 简单的解决方案是在分隔符上拆分。见yate's answer

标签: javascript regex regex-group


【解决方案1】:

听起来您只想用:, 分割字符串。这行得通吗?

var str = "123:test,south-west,best,rest_well";
var res = str.split(/:|,/);

输出

["123", "test", "south-west", "best", "rest_well"]

【讨论】:

  • 嘿,这是一个非常好的解决方案!我只需添加以下测试来验证格式: var re = new RegExp(/^\d+:[a-zA-Z0-9_\-]+(?:,[a-zA-Z0-9_\-] +)*$/), str = '123:test,south-west,best,rest_well', res = null; if (re.test(str)) { res = str.split(/:|,/) } else { res = []; }
猜你喜欢
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 2011-12-12
  • 1970-01-01
  • 2012-01-02
  • 2010-10-14
相关资源
最近更新 更多