Linux 正则表达式 [] 之间的任何内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3677255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex for anything between []
提问by Ankit
I need to find the regex for []
我需要找到 [] 的正则表达式
For eg, if the string is - Hi [Stack], Here is my [Tag] which i need to [Find].
例如,如果字符串是 - Hi [Stack],这是我需要 [Find] 的 [Tag]。
It should return Stack, Tag, Find
它应该返回堆栈、标记、查找
采纳答案by John Kugelman
Pretty simple, you just need to (1) escape the brackets with backslashes, and (2) use (.*?)
to capture the contents.
非常简单,您只需要 (1) 用反斜杠转义括号,以及 (2) 用于(.*?)
捕获内容。
\[(.*?)\]
The parentheses are a capturing group, they capture their contents for later use. The question mark after .*
makes the matching non-greedy. This means it will match the shortest match possible, rather than the longest one. The difference between greedy and non-greedy comes up when you have multiple matches in a line:
括号是一个捕获组,它们捕获其内容供以后使用。后面.*
的问号使匹配非贪婪。这意味着它将匹配最短的匹配项,而不是最长的匹配项。当一行中有多个匹配项时,贪婪和非贪婪之间的区别就出现了:
Hi [Stack], Here is my [Tag] which i need to [Find].
^______________________________________________^
A greedy match will find the longest string possible between two sets of square brackets. That's not right. A non-greedy match will find the shortest:
贪婪匹配将在两组方括号之间找到可能的最长字符串。那是不对的。非贪婪匹配将找到最短的:
Hi [Stack], Here is my [Tag] which i need to [Find].
^_____^
Anyways, the code will end up looking like:
无论如何,代码最终看起来像:
string regex = @"\[(.*?)\]";
string text = "Hi [Stack], Here is my [Tag] which i need to [Find].";
foreach (Match match in Regex.Matches(text, regex))
{
Console.WriteLine("Found {0}", match.Groups[1].Value);
}
回答by Femaref
\[([\w]+?)\]
should work. You might have to change the matching group if you need to include special chars as well.
应该管用。如果您还需要包含特殊字符,则可能需要更改匹配组。
回答by Michel de Ruiter
Depending on what environment you mean:
取决于你的意思是什么环境:
\[([^\]]+)]
回答by Mike
.NET syntax, taking care of multiple embedded brackets:
.NET 语法,处理多个嵌入式括号:
\[ ( (?: \\. | (?<OPEN> \[) | (?<-OPEN> \]) | [^\]] )*? (?(OPEN)(?!)) ) \]
\[ ( (?: \\. | (?<OPEN> \[) | (?<-OPEN> \]) | [^\]] )*? (?(OPEN)(?!)) ) \]
This counts the number of opened [
sections in OPEN
and only succeeds if OPEN
is 0 in the end.
这会计算打开的[
部分的数量,OPEN
并且只有OPEN
最终为 0 时才会成功。
回答by Victor S
I encountered a similar issue and discovered that this also does the trick.
我遇到了类似的问题,发现这也能解决问题。
\[\w{1,}\]
The \wmeans Metacharacter. This will match 1 or more word characters.
该\ W手段元字符。这将匹配 1 个或多个单词字符。
Using n{X,}quantifier matches any string where you can obtain different amounts. With the second number left out on purpose, the expression means 1 or more characters to match.
使用n{X,}量词匹配您可以获得不同数量的任何字符串。故意省略第二个数字,表达式意味着要匹配 1 个或多个字符。