Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression: first character alphabet second onward numeric

Tags:

c#

regex

This is my string, which always starts with a alphabet followed by 3 digits, then - (hyphen), followed by 3 digits, then alphabet, then 4 digits

I123-123S1234N1234

I have come up with a regular expression, which seems to be very long! How can I write a better expression for this?

[a-zA-Z][0-9][0-9][0-9][-][0-9][0-9][0-9][a-zA-Z].........goes on

Note

  • Shall support case insensitive
  • Hyphen, S and N always constant
like image 295
kudlatiger Avatar asked Jul 09 '26 05:07

kudlatiger


2 Answers

Try this:

var testString = "I123-123S1234N1234";
var pattern = @"[A-Za-z]\d{3}-\d{3}[sS]\d{4}[nN]\d{4}";
var isMatch = Regex.Match(testString, pattern).Success;

Pattern used: [A-Za-z]\d{3}-\d{3}[sS]\d{4}[nN]\d{4}

Explanation:

[A-Za-z] - match any letter

\d{3} - match three digits

[sS] - match S or s literally

\d{4} - match four digits

[nN] - match N or n literally

\d{4} - match four digits

like image 168
Michał Turczyn Avatar answered Jul 10 '26 18:07

Michał Turczyn


First use the case-insensitive flag, and then when repeating tokens, use {<number of times to repeat>}` instead of repeating yourself:

(?i)[a-z][0-9]{3}-[0-9]{3}[a-z][0-9]{4}

If you want to match the trailing N1234 as well, then put the final [a-z][0-9]{4} in a group, and repeat it twice:

(?i)[a-z][0-9]{3}-[0-9]{3}(?:[a-z][0-9]{4}){2}

https://regex101.com/r/5ra1eU/1

If the S and N are constant, then don't use character sets to match them, just match the plain characters:

(?i)[a-z][0-9]{3}-[0-9]{3}S[0-9]{4}N[0-9]{4}

https://regex101.com/r/5ra1eU/2

like image 36
CertainPerformance Avatar answered Jul 10 '26 20:07

CertainPerformance