简体   繁体   中英

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 pattern unless it preceeds with parenthesis and letters (?<!\\([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:

(?<!\()\bRR?US? ?2217 ?B7

Explanation

  • (?<!\\() Negative lookbehind to assert what is on the left is not (
  • \\b Word boundary
  • RR?US? ?2217 ?B7 RR?US? ?2217 ?B7 Match your pattern

See a .NET regex demo | C# demo

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM