首页 > 解决方案 > 正则表达式分别匹配方括号中的文本

问题描述

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

// 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?" ]

我究竟做错了什么?

标签: javascriptregex

解决方案


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

这是产生您正在寻找的结果的版本:

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);


推荐阅读