Reputation: 893
I am trying to create regex to exactly match one string format. The strings will be like this
A3476,TextA B5628,TextB A9871,TextC
The first character should be either 'A' or 'B' and it will follow integer number which should be exactly 4 chars in length and followed by ','. After comma only Three words will repeate those are either 'TextA' or 'TextB' or 'TextB'.
I have tried this regex
(A|B)(\d{4})(,)(TextA|TextB|TextC)
When I add any alphabet in the integer number or integer number is greater than 4 chars in length the string match should fail but it is not failing.
Suppose if the string is like this
A653k7876,TextA
I am getting result like this 7876,TextA
. The result is missing character 'A' and reading integer from end. My intention is it should fail.
Upvotes: 1
Views: 62
Reputation: 7524
Looks like we need more info, as if I use strings exactly as you provided they work fine:
Console.WriteLine(Regex.IsMatch(@"A653k7876,TextA", @"(A|B)(\d{4})(,)(TextA|TextB|TextC)"));
outputs False - as you want.
Upvotes: 0
Reputation: 50346
Your regex is fine, except that you should indicate where it should start and end with the match. The ^
special character indicates the start of a line or string, and $
the end. So, try this instead:
^(A|B)(\d{4})(,)(TextA|TextB|TextC)$
Make sure you specify RegexOptions.Multiline
when creating the Regex
object to make this work.
Upvotes: 1
Reputation: 2005
Use:
\b(A|B)(\d{4}),(TextA|TextB|TextC)\b
\b denotes the word boundary
You might find this link useful: C# Regex Cheat Sheet
Upvotes: 0