[英]Regex to match contents of a string preceded by particular string and ended with a particular string
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[first_name][value]
返回字符串first_name
。
Block[last_name][value]
returns the string last_name
. Block[last_name][value]
返回字符串last_name
。
What I've tried: 我尝试过的
This was my current regex: http://regex101.com/r/jW0hY1/1 这是我当前的正则表达式: http : //regex101.com/r/jW0hY1/1
/(?:Block\\[).*(?:\\[value])/
I figured first I'd have a non-capturing match for Block[
. 我首先想到了对
Block[
进行非捕获式匹配。 Then I would capture all the content until ][value]
began. 然后,我将捕获所有内容,直到
][value]
开始为止。 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... 编辑:和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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.