Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C#
I need to write a regex for below scenario:
First four characters must be letters including "Ñ" or "&".
Next two characters must be digits.
Next character must be 0 or 1.
Next character must be digit.
Next two characters must be from 01 to 31.

I have a regex, but this is failing:
var regexTenCharacter = new RegExp("[A-Za-zÑ&]{4}[0-9]{2}[0|1]{1}[0-9]{1}[0-3]{1}[0-9]{1}$");

Please provide a workaround for this.


What I have tried:

var regexTenCharacter = new RegExp("[A-Za-zÑ&]{4}[0-9]{2}[0|1]{1}[0-9]{1}^(3[01]|[12][0-9]|[1-9])$");
Posted
Updated 19-May-16 13:31pm

Your regex looks awfully close. Try:
JavaScript
var regexTenCharacter = new RegExp("^[A-Za-zÑ&]{4}\d{2}[01]\d(?:(?:0[1-9])|(?:[12]\d)|3[01])$");

All of the {1} are unnecessary since exactly 1 occurrence of an item is the default.
You had [0|1] where all you wanted was [01].
What you had would match any of the three characters: 0 1 | (vertical bar)
Your handling at the end would have allowed any 2 digit number from 00-39.
It needs to be a bit more specific, piecewise, to get the range you want.

There's also Expresso[^] for building and testing regular expressions.

Also, you said that what you had was failing but you weren't specific about what was wrong. You should always be as specific as possible describing your errors.
 
Share this answer
 
Comments
George Jonsson 19-May-16 19:45pm    
+5
Matt T Heffron 19-May-16 19:51pm    
Thanks
To test RegEx, I use these sites
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
.NET Regex Tester - Regex Storm[^]
In both you can paste a RegEx and some data and see what match.
The first one also show your RegEx as a diagram that show you what does the expression. By using a cursor, you can see the matching progress in regEx and data at same time. So you can see where it fail and why.

-Did you try to remove the '$' ?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900