正则表达式分别匹配方括号中的文本

时间:2019-08-15 22:13:46

标签: javascript regex

我正在尝试分别匹配方括号中的文本。

// What I did: 
const regex = /(\w|\[|\.|,|:|\$)+(?:\s\w+)*(\]|\]|\?|')?/g;
const testString = `This] is a test [string] with [a test that is, obio'u for a $1000?`;
const strings = testString.match(regex);

console.log(strings);

// What I am getting
// [ "This]", "is a test", "[string]", "with", "[a test that is", ", obio'", "u for a", "$1000?" ]

// What I want
// [ "This]", "(a space)is a test(a space)", "[string]", "(a space)with(a space)", "[a test that is, obio'u for a $1000?" ]

我在做什么错?

1 个答案:

答案 0 :(得分:1)

您的正则表达式不允许以空格开头的匹配项。为什么期望第二个匹配的字符串以空格开头?

这里是产生您想要的结果的版本:

const testString = `This] is a test [string] with [a test that is, obio'u for a $1000?`;
const strings = testString.match(/[^\]][^\[\]]*\]?|\]/g);

console.log(strings);