在字符串中找到`'('+任何数字+')'`并拆分JavaScript

时间:2019-02-27 13:13:32

标签: javascript arrays

如何在字符串中找到'('+any number+')',将字符串拆分为数组,就像我有此文本一样

"(1)some words (2)other words (3)other words (4)other words ...."

这是我尝试过的someString.split(/[0-9]/)

结果:"(" ")some words (" ")other words (" ")other words (" ")other words"

这似乎只能找到0到9之间的数字

我需要类似('('+/[0-9]/+')')

的东西

2 个答案:

答案 0 :(得分:0)

\d+\(\d+\)上使用正则表达式

console.log( 
  "(1)some words  (2)other words (3)other words (4)other words .... (10)end"
  .match(/\d+/g) // or \d{1,}
)

仅在使用捕获组的括号中:

const re = /\((\d+)\)/g;
while (match = re.exec("(1)some words  (2)other words (3)other number 3 words (4)other words .... (10)end")) {
  console.log(match[1])
}

答案 1 :(得分:0)

假设您实际上要以一个术语而不是数字结尾,我们可以尝试对模式\(\d+\)进行正则表达式拆分:

input = "(1)some words  (2)other words (3)other words (4)other words ....";
terms = input.split(/\(\d+\)/);
terms.shift();
console.log(terms);

您遇到了一些问题,但是关于您当前的拆分为何仅针对0-9的原因,这是因为正则表达式模式[0-9]仅表示0到9。使用[0-9]+\d+定位到任意数字。