首页 > 解决方案 > 在字符串中查找 `'('+any number+')'` 并拆分 JavaScript

问题描述

我如何'('+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]/+')')

标签: javascriptarrays

解决方案


\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])
}


推荐阅读