简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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