1

How can I make a regex that would extract the the contents of the first square brackets in the following?

Block[first_name][value] returns the string first_name.

Block[last_name][value] returns the string last_name.

What I've tried:

This was my current regex: http://regex101.com/r/jW0hY1/1

/(?:Block\[).*(?:\[value])/

I figured first I'd have a non-capturing match for Block[. Then I would capture all the content until ][value] began. Instead this seems to return the entire string.

Don P
  • 60,113
  • 114
  • 300
  • 432

3 Answers3

0

Get the matched group from index 1.

(?:Block\[)([^\]]*)(?:\]\[value\])

DEMO


OR make some changes in your regex

(?:Block\[)(.*)(?:\]\[value])

DEMO

Braj
  • 46,415
  • 5
  • 60
  • 76
0

The problem is that .* eats up as many characters as it can. Use a non greedy quantifier instead, and a capture group:

Block\[(.*?)\]

If you need to capture the value too, you can use this expression:

Block\[(.*?)\]\[(.*?)\]

EDIT: And the JS...

var re = /Block\[(.*?)\]\[(.*?)\]/g;
var match;
while(match = re.exec("Block[first_name][value] Block[last_name][value]")) {
    console.log("Found " + match[1] + " with value: " + match[2]);
}
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
0

Regular expression: (DEMO)

(?:Block\[)(.*)(?:\]\[value])

Getting the content:

string = "Block[first_name][value]";
result = string.match((/?:Block\[)(.*)(?:\]\[value])/, g);
console.log(result[1]); //first_name
Michael Parker
  • 12,724
  • 5
  • 37
  • 58