Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# regular expression ignores extra data at ends

Tags:

c#

regex

I'm trying to build a regex in C# that has the following characteristics.

  1. The string starts with zero or more numbers
  2. Followed by the letters "ABC"
  3. Followed by the end of the string

I've tried

\d?ABC

but still matches things like ZABC, ABCD, 2ZABC.

any pointers?

like image 740
neeljpatel Avatar asked Dec 14 '12 19:12

neeljpatel


1 Answers

You need anchors to represent the start and end of the string:

^\d?ABC$

Also, ? means 0 or 1. 0 or more is *:

^\d*ABC$

Also note that depending on the active Culture in .NET \d can be interpreted as "any Unicode digit character". If you really only want the ASCII digits use a character class:

^[0-9]*ABC$

The tutorial on that website is a great resource to learn regular expressions.

like image 111
Martin Ender Avatar answered Oct 06 '22 16:10

Martin Ender