正则表达式给出不正确的结果



在Javascript中工作,尝试使用正则表达式来捕获字符串中的数据。

我的字符串从左括号开始显示为这样

['ABC']['ABC.5']['ABC.5.1']

我的目标是将正则表达式的每一部分作为块或数组获取。 我已经审查并看到匹配功能可能是一个不错的选择。

var myString = "['ABC']['ABC.5']['ABC.5.1']";
myString.match(/[/g]);

我看到的输出只是每个元素的 [。

例如,我希望数组是这样的

myString[0] = ['ABC']
myString[1] = ['ABC.5']
myString[2] = ['ABC.5.1']

获得上述所需输出的正确正则表达式和/或函数是什么?

如果你只想将它们分开,你可以使用一个简单的表达式,或者更好的是你可以拆分它们:

['(.+?)']

const regex = /['(.+?)']/gm;
const str = `['ABC']['ABC.5']['ABC.5.1']`;
const subst = `['$1']n`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

演示

您可以将此正则表达式与拆分一起使用:

[[^]]+

  • [- 比赛[
  • [^]]+- 匹配除]一次或多次之外的任何内容
  • ]- 比赛]

let str =  `['ABC']['ABC.5']['ABC.5.1']`
let op = str.split(/([[^]]+])/).filter(Boolean)
console.log(op)

最新更新