[英]Match an specific expression not between parenthesis in C#
as shown in below I have a string which is contain serial number of some items inside or out of parenthesis . 如下所示,我有一个字符串,其中包含括号内或括号外某些项目的序列号。 How can I match items just out of parenthesis ? 如何匹配括号之外的项目?
string text = "RRUS 2217 B7 (RRUS 2217 B7)";
string pattern = "[^(]RR?US? ?2217 ?B7";
foreach(Match match in Regex.Matches(text, pattern))
{
Console.WriteLine(match.Value);
}
but output in console is as below: 但是控制台中的输出如下:
RRUS 2217 B7
RRUS 2217 B7
Try looking behind : match every RR?US? ?2217 ?B7
尝试往后看 :匹配每个RR?US? ?2217 ?B7
RR?US? ?2217 ?B7
pattern unless it preceeds with parenthesis and letters (?<!\\([AZ]*)
: RR?US? ?2217 ?B7
模式,除非它以括号和字母(?<!\\([AZ]*)
开头:
string text = "RRUS 2217 B7 (RRUS 2217 B7)";
string pattern = @"(?<!\([A-Z]*)RR?US? ?2217 ?B7";
foreach(Match match in Regex.Matches(text, pattern))
{
Console.WriteLine(match.Value);
}
Your pattern starts with a word character. 您的模式以单词字符开头。 Another option could be to make use of the negative lookbehind (?<!\\()
to assert what is on the left is not a (
and use a word boundary \\b
at the start of the match: 另一个选择可能是利用否定式(?<!\\()
断言左边不是a (
并在比赛开始时使用单词边界\\b
:
(?<!\()\bRR?US? ?2217 ?B7
Explanation 说明
(?<!\\()
Negative lookbehind to assert what is on the left is not (
(?<!\\()
否定向后断言左侧的内容不是(
\\b
Word boundary \\b
字边界 RR?US? ?2217 ?B7
RR?US? ?2217 ?B7
Match your pattern RR?US? ?2217 ?B7
符合您的样式 See a .NET regex demo | 查看.NET regex演示 | C# demo C#演示
Another way could be to match what you don't want and to capture in a group what you do want: 另一种方法是匹配您不想要的内容,并在组中捕获您想要的内容:
\(RR?US? ?2217 ?B7\)|(RR?US? ?2217 ?B7)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.