J.Jay
J.Jay

Reputation: 249

Match and capture the (capital) letters inside the square brackets

I'm fairly new to regex and I'd like to know the pattern to match and capture the letters inside the square brackets. For example, I'd like to capture DATA from the string below. My sample code's as below:

var myString = "testing/node/234 test_TEST [1234] testing [DATA] SUMMARY,VALUES,abcd,1,0,0";
var re = new RegExp("\[([A-Z]+)\]");
var match = re.exec(myString);
console.log(match[1]);

It's giving me a syntax error: * Unmatched ')' * at the second line.

Upvotes: 0

Views: 2112

Answers (3)

Downgoat
Downgoat

Reputation: 14371

The "best" way in my opinion would be a look behind and a lookahead

(?<=\[)[A-Z]+?(?=\])

This will avoid selecting the brackets also

Or perhaps:

\[([A-Z]+?)\]

in a more limited flavor

Upvotes: 0

Mathieu David
Mathieu David

Reputation: 5278

Depending on how similar the tested strings are and how strict you want your regex, you have multiple choices from less strict to more strict:

  1. Simply match something between square brackets:

    \[(.+)\]
    

    You will probably want a non-greedy regex, in this case. Because if there were 2 different things between brackets e.g. [AB] some text [CD] it would capture AB] some text [CD. The non-greedy flag will prevent this.

  2. match square brackets after closing parenthesis and space:

    \)\s\[(.+)\]
    
  3. match the square brackets after exactly 3 words:

    (?:[^\s]+\s){3}\[(.+)\]
    

You can still go stricter depending on your needs, but you get the point.

Stricter regex will prevent accidentally matching something you didn't expect. For example if test_module would have been [test_module] the first regex would have matched that, the other two would not have.

This is particularly important when the string is completely or even partially composed by user input. Never trust the user ;)

Upvotes: 3

Rakholiya Jenish
Rakholiya Jenish

Reputation: 3223

Try using:

\[([A-Z]+)\]

To capture the brackets with capital letters only.

Two match two or more strings into the brackets, use /g for global selection.

Upvotes: 4

Related Questions