Javascript 正则表达式分别匹配方括号中的文本
我试图分别匹配方括号中的文本Javascript 正则表达式分别匹配方括号中的文本,javascript,regex,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); // Wh
// 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?" ]
我做错了什么 您的正则表达式不允许以空格开头的匹配。为什么希望第二个匹配的字符串以空格开头 以下是一个版本,可生成您要查找的结果: const testString=`This]是一个测试[string],其中包含[a test,即$1000的obio'u?`; const strings=testString.match/[^\][^\[\]*\]?\\]/g; console.logstrings;可能重复的