0

I want to match a sequence of alphabets and any number of digits seperated by a '-' . For example ABC-1, ABC-12, ABC-123, ABC-1234 and so on..... I looked at an example Regex for numbers only and https://msdn.microsoft.com/en-us/library/3y21t6y4(v=vs.110).aspx .I got a code below.

var regex = new Regex($@"^[A - Z]{{{numberOfLettersBeforeHyphen}}}-\d+");
return regex.IsMatch(stringToMatch);

where numberOfLettersBeforeHyphen = 3 but it always return false for the above examples. Please point out where the mistake lies, which will help me to accomplish my goal. Thank you all

Abhishek Kumar
  • 342
  • 5
  • 22

1 Answers1

1

Spaces are meaningful in the pattern, that's why in your current code

 ... Regex($@"^[A - Z]...");

means in a range from space to space. Drop spaces:

 var regex = new Regex($@"^[A-Z]{{{numberOfLettersBeforeHyphen}}}-[0-9]+");
 ...  

P.S. [0-9]: in .Net \d means any unicode digit, e.g. Persian one (۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹); I've put [0-9] in order to exclude them. You may want to add yet another anchor: $ (in case the entire string should match the pattern):

 var regex = new Regex($@"^[A-Z]{{{numberOfLettersBeforeHyphen}}}-[0-9]+$");
 ...
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Wasn't aware of the unicode implications of \d in C#. Everyday something new, thanks Dmitry! +1 – Fildor Jan 09 '18 at 08:22