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.
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]);
}
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
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.