Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I know I am going to kick myself when I see the answer, but I have been playing with this for an hour and can't figure out how to write a regular expression to accept 1-14 digits in a single-line string and reject anything else. This is for use inside a WPF ValidationRule.

Note that this is not attempting to find such sub-strings in a body of text; it is intended to reject anything that does not fit the pattern, so 01234567890123 is fine but 01234567890123X is not.

What I have tried:

None of these work:

^[0-9]{1,14}$

[0-9]{1,14}$

^[0-9]{1,14}

[0-9]{1,14}

This almost works...

\b[0-9]{1,14}\b

...but for some reason will accept an open bracket, so it will match 1234(, which it should reject.
Posted
Updated 20-Jun-17 23:49pm
v3
Comments
Tomas Takac 21-Jun-17 5:46am    
You should update your question with the code you use for testing. FYI ^[0-9]{1,14}$ works as expected for me with the examples you gave.

Quote:
^[0-9]{1,14}$

This one should do. Your fail have another reason. You should give more details.

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
Share this answer
 
v2
Comments
Patrick Skelton 21-Jun-17 7:19am    
The expression above does indeed work as expected using the excellent Debuggex (thank you for the link). And, when I go back into code, I find that it does indeed now work as expected. Maybe I was somehow testing a different piece of code to the one I was editing. Doh! I take the earlier point by Tomas, that I should have included some test code, which would quickly have indicated that something other than the regular expression was to blame. Thank you all for the help.
^[0-9]{1,14}$

The problem however is about how the Regex engine interprets ^ and $...
If you are in single-line mode the engine look at the input as a single line and ^ and $ means the beginning and the end of the whole input!
In multi-line mode (/m or RegexOptions.Multiline[^]) the mmenaing of ^ and $ changes and it is now the beginning and the end of line within the whole input...
C#
Regex oRegex = new Regex("^[0-9]{1,14}$", RegexOptions.Multiline);
 
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