【问题标题】:How to Capture Repeating Groups at end of Asymmetrical Expression如何在不对称表达结束时捕获重复组
【发布时间】:2017-10-28 22:36:33
【问题描述】:

我知道存在很多关于捕获组的现有问题,我已经阅读了大约十几个,但我似乎无法解决我遇到的问题。我有一个这种形式的字符串:
{{First String/Second String|{Thing1}|{Thing2}|{Thing3}|{Thing4}|}}
第一部分是固定的,但对于 {Thingx} 部分,可以是从 0 到 n 的任意值。我想得到一个数组
全场比赛
第一个字符串
第二个字符串
东西1
东西2
东西3
东西4

我正在使用 regex101.com 进行测试。我有一个initial regex
/{{(.+?)\/(.+?)\|({.+?}\|)}}/
可以将所有{Thingx} 片段捕获为一个组。然后我可以使用second regex
/{(.*?)}\|/
打破他们。是否有一个正则表达式可以同时执行这两个步骤?

【问题讨论】:

  • {Thingx} portion there can be anywhere from 0 to n 那么这不能用一个正则表达式来完成。 Thingx 必须全部捕获在一个组中。比赛结束后,该组可以用另一个正则表达式进一步细分,两个数组可以在其中连接。所以,NO不可能一步到位。

标签: javascript regex


【解决方案1】:

如何依靠多个匹配而不是组。您可以使用布尔值OR| 在一行中的正则表达式中实现这一点。正则表达式是

{{([^\/]*)|\/(.*?)\||{(.*?)}

一个完整的例子可能是这样的

var str = '{{First String/Second String|{Thing1}|{Thing2}|{Thing3}|{Thing4}|}}';
var myRegexp = /{{([^\/]*)|\/(.*?)\||{(.*?)}/g;
var match = myRegexp.exec(str);
while (match != null) {
  if (typeof match[1] != 'undefined') console.log(match[1])
  if (typeof match[2] != 'undefined') console.log(match[2])
  if (typeof match[3] != 'undefined') console.log(match[3])
  console.log("---------------------------");
  match = myRegexp.exec(str);
}

【讨论】:

  • 完美。我必须更加熟悉多重匹配的概念。这将是一个很好的干净解决方案。
猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 2017-09-13
  • 2011-03-11
  • 2017-01-07
  • 2019-12-19
相关资源
最近更新 更多