I would like to use regex to match a string of exactly 2 characters, and both of those characters have to be between 0 and 9. The string to match against would be coming from a single-line text input field when an ASP.NET MVC view is rendered
So far, I have the regex
[0-9]{2}
and from the following list of example string inputs
the following matches are returned when I apply the regex
So, I have kind of half the solution....what I actually want to enforce is that the string is also exactly 2 characters long, so that from the list of strings, the only one that should be matched is
12
I am an admitted amateur at regular expressions and am just using this to validate a card issue number on an ASP.NET MVC model as below....
[Required] [RegularExpression("[0-9]{2}")] public string IssueNumber { get; set; }
I'm sure that what i'm asking is quite simple but I wasn't able to find any examples that limited the length as part of the matching .
Thanks, in advance.
To match a two digit number / \d{2} / is used where {} is a quantifier and 2 means match two times or simply a two digit number. Similarly / \d{3} / is used to match a three digit number and so on.
To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything.
Definition and UsageThe [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.
You can use the start (^
) and end ($
) of line indicators:
^[0-9]{2}$
Some language also have functions that allows you to match against an entire string, where-as you were using a find
function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^
and $
will be redundant.
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