匹配最后一个括号

时间:2016-04-24 09:40:14

标签: c# regex

我有一个$(document).on('change', "body", function(){ $( ".ui-selectmenu" ).selectmenu(); }); ,其中包含一些文字,后跟一些包含不同内容的括号(可能为空)。我需要提取其内容的最后一个括号:

string

我已查看atext[d][][ef] // should return "[ef]" other[aa][][a] // should return "[a]" xxxxx[][xx][x][][xx] // should return "[xx]" yyyyy[] // should return "[]" 并阅读了lazy vs greedy matching,但我无法为我的生活做好准备。

4 个答案:

答案 0 :(得分:3)

这个正则表达式将起作用

.*(\[.*\])

<强> Regex Demo

更有效率和非贪婪的版本

.*(\[[^\]]*\])

C#代码

string input = "atext[d][][ef]\nother[aa][][a]\nxxxxx[][xx][x][][xx]\nyyyyy[]";
string pattern = "(?m).*(\\[.*\\])";
Regex rgx = new Regex(pattern);

Match match = rgx.Match(input);

while (match.Success)
{
    Console.WriteLine(match.Groups[1].Value);
    match = match.NextMatch();
}

<强> Ideone Demo

嵌套[]或不平衡[]

可能会产生意外结果

答案 1 :(得分:0)

或者,您可以使用与此类似的函数来反转字符串:

public static string Reverse( string s )
{
    char[] charArray = s.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}

然后你可以执行简单的正则表达式搜索,只查找第一个[someText]组,或者只使用for循环迭代,然后在到达第一个]时停止。

答案 2 :(得分:0)

负向前瞻:

colnames(mydfm)

这是相对有效和灵活的,没有邪恶的\[[^\]]*\](?!\[) 。这也适用于包含多个实例的较长文本。

<强> Regex101 demo here

答案 3 :(得分:0)

.net的正确方法确实是使用正则表达式选项RightToLeft和适当的方法Regex.Match(String, String, RegexOptions)

通过这种方式,您可以保持模式非常简单和高效,因为它不会产生较少的回溯步骤,并且由于模式以文字字符(结束括号)结束,因此可以快速进行在正则表达式引擎的“正常”行走之前,搜索模式可能成功的字符串中的可能位置。

public static void Main()
{
    string input = @"other[aa][][a]";

    string pattern = @"\[[^][]*]";

    Match m = Regex.Match(input, pattern, RegexOptions.RightToLeft);

    if (m.Success)
        Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index);
}