否定字符类的C#正则表达式,除非字符彼此相邻 [英] C# regex for negated character class unless chars are next to one another

查看:165
本文介绍了否定字符类的C#正则表达式,除非字符彼此相邻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要匹配字符串中最里面的括号之间的字符,但允许使用空括号,例如'()'.尽我所能告诉我这里需要进行某种否定的前瞻(这与标记为重复的问题完全不同)

I need to match the characters between the innermost set of parentheses in a string, but allowing empty parens such as '()'. As best I can tell some kind of negative lookahead is needed here (and it is completely different than the question for which it is marked as duplicate)

正确包含'()'的初始版本为:

An initial version, which does not properly include '()' is:

var re = new Regex(@"\(([^()]+)\)");

一些测试示例:

x (a) y          -> a
x (a b) y        -> a b
x (a b c) y      -> a b c
x (a b() c) y    -> a b() c
x (a() b() c) y  -> a() b() c
x (a b() c()) y  -> a b() c()
x (a b(a) c) y   -> a
x (a (b() c)) y  -> b() c
x () y           -> empty

 

还有一个c#测试方法(适用于您的断言库):

And a c# test method (adapt for your assertion library):

var re = new Regex(@"\(([^()]+)\)");

string[] tests = {
    "x (a) y", "a",
    "x (a b) y", "a b",
    "x (a b c) y", "a b c",
    "x (a b() c) y", "a b() c",
    "x (a() b() c) y", "a() b() c",
    "x (a b() c()) y", "a b() c()",
    "x (a b(a) c) y", "a",
    "x (a (b() c)) y", "b() c",
    "x () y", ""
};

for (int i = 0; i < tests.Length; i+=2)
{
    var match = re.Match(tests[i]);
    var result = match.Groups[1].Value;
    Assert.That(result, Is.EqualTo(tests[i + 1]));
}

推荐答案

您可以使用以下代码:(无需环顾四周)

You could use something like this: (No need for Lookarounds)

\(((?:[^()]|\(\))+)\)

对正则表达式的调整:

在非捕获组中添加了[^()]以及备用|\(\),因此它可以匹配 () 以外的其他字符或空括号().

Added the [^()] in a non-capturing group along with an alternative |\(\) so it can match either a character other than ( and ) or empty parentheses ().

在线试用.

或者,如果不需要捕获组 ,则可以将其删除,并使用类似的Lookarounds使匹配项完全匹配而不是分组:

Alternatively, you could get rid of the capturing group if you don't need it and have your matches in full matches instead of groups by using Lookarounds like this:

(?<=\()(?:[^()]|\(\))+(?=\))

这样,您可以直接使用match.Value而不是match.Groups[1].Value来访问比赛.

That way, you can access your matches directly using match.Value instead of match.Groups[1].Value.

这是一个演示.

请让我知道是否有任何不清楚的地方.

Please let me know if there's anything not clear.

这篇关于否定字符类的C#正则表达式,除非字符彼此相邻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆