正则表达式用于[]之间的任何内容 [英] Regex for anything between []
问题描述
我需要找到[]的正则表达式
I need to find the regex for []
例如,如果字符串为-[Stack]这是我需要[查找]的[Tag].
For eg, if the string is - Hi [Stack], Here is my [Tag] which i need to [Find].
它应该返回堆叠,标记,查找
It should return Stack, Tag, Find
推荐答案
非常简单,您只需要(1)用反斜杠转义括号,(2)使用(.*?)
捕获内容.
Pretty simple, you just need to (1) escape the brackets with backslashes, and (2) use (.*?)
to capture the contents.
\[(.*?)\]
括号是一个捕获组,它们捕获其内容供以后使用..*
之后的问号使匹配的内容变得非贪婪.这意味着它将匹配可能的最短匹配,而不是最长匹配.当一行中有多个匹配项时,贪婪和非贪婪的区别就会出现:
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);
}
这篇关于正则表达式用于[]之间的任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!