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
S and N always constantTry 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With