简体   繁体   English

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

[英]Regex match text in square brackets separately

I'm trying to match the text in the square brackets separately. 我正在尝试分别匹配方括号中的文本。

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

What am I doing wrong? 我究竟做错了什么?

Your regex does not allow a match that starts with a space. 您的正则表达式不允许以空格开头的匹配项。 Why do you expect the second matched string to start with a space? 为什么期望第二个匹配的字符串以空格开头?

Here is a version that produces the results you're looking for: 这是产生您想要的结果的版本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM