JavaScript中的正则表达式替换,其中某些部分保持不变

问题描述 投票:0回答:1

我需要解析一个像这样的字符串:

-38419-indices-foo-7119-attributes-10073-bar

其中有数字,后面跟着一个或多个单词,都由破折号连接起来。我需要得到这个:

[ 
   0 => '38419-indices-foo',
   1 => '7119-attributes',
   2 => '10073-bar',
]

我曾想过尝试用:替换仅数字前的破折号,然后使用.split(':')-我该怎么做?我不想替换其他破折号。

javascript regex backreference
1个回答
1
投票

Imo,模式很简单:

\d+\D+

为了摆脱尾随的-,您可以寻求

(\d+\D+)(?:-|$)

您可以在这里看到它:

var myString = "-38419-indices-foo-7119-attributes-10073-bar";
var myRegexp = /(\d+\D+)(?:-|$)/g;
var result = [];
match = myRegexp.exec(myString);
while (match != null) {
  // matched text: match[0]
  // match start: match.index
  // capturing group n: match[n]
  result.push(match[1]);
  match = myRegexp.exec(myString);
}

console.log(result);


demo on regex101.com
© www.soinside.com 2019 - 2024. All rights reserved.