skip to Main Content

I have the following string:

  • [I need some fresh air H2O].

What’s the RegEx that matches the following words?

  • I, need, some, fresh, air, H2O.

Basically, each word inside the square brackets. I searched everywhere, couldn’t find it. Every result points to a whole match, such as I need some fresh air H2O (check links below).

Can anyone help?

I’m currently at this RegEx:

  • (?<=[).+?(?=])

But it captures the whole sentence:

  • I need some fresh air H2O

I’m using the https://regexr.com/ engine (I assume it’s javascript), but any engine pattern would suffice.

Related Questions

Regular expression to extract text between square brackets

regex include text inside brackets

2

Answers


  1. You can use str.slice(1, -1).split(/s+/) or match() method using:

    • /bw+b/g: b is a word boundary.

    • /[^[]rns]+/g: means all chars except those included in the [].

    let str = "[I need some fresh air H2O]";
    console.log(str.match(/bw+b/g));
    console.log(str.slice(1, -1).split(/s+/));
    console.log(str.match(/[^[]rns]+/g));

    Prints

    [ 'I', 'need', 'some', 'fresh', 'air', 'H2O' ]
    [ 'I', 'need', 'some', 'fresh', 'air', 'H2O' ]
    [ 'I', 'need', 'some', 'fresh', 'air', 'H2O' ]
    
    
    Login or Signup to reply.
  2. It’s rather simple to match all words in a string: w+

    w matches alphanumeric characters and underscores. This assumes that you use a "global search" which repeatedly applies the pattern on the remaining string after each match. In javascript this would be /w+/g.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search