0

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?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Testaccount
  • 2,755
  • 3
  • 22
  • 27
  • Possible duplicate of [Regular expression to extract text between square brackets](https://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets) – vs97 Aug 15 '19 at 22:56

1 Answers1

1

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);
melpomene
  • 84,125
  • 8
  • 85
  • 148