Reputation: 21
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
Upvotes: 1
Views: 63
Reputation: 163277
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 boundaryRR?US? ?2217 ?B7
Match your patternSee 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)
Upvotes: 1
Reputation: 186668
Try looking behind: match every RR?US? ?2217 ?B7
pattern unless it preceeds with parenthesis and letters (?<!\([A-Z]*)
:
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);
}
Upvotes: 1