Reputation: 7309
I generally stay away from regular expressions
because I seldom find a good use for them. But in this case, I don't think I have choice.
I need a regex for the following situation. I will be looking at three character strings. It will be a match if the first character is 1-9 or the letters o,n,d (lower or upper)
AND the second character is 1,2 or 3
and the third character is 0-9
.
Can anybody help me out?
Upvotes: 1
Views: 9959
Reputation: 2899
Perl RegEx: /^[1-9ondOND][1-3][0-9]$/
^
at the start of the string;
$
at the end of the string.
Upvotes: 2
Reputation: 5655
A very late answer, but hope this will help
([1-9]|(?i)(o|n|d))[123][\d]
http://regex101.com/r/vE2jT1/1
Upvotes: 0
Reputation: 242100
[1-9ondOND][123][0-9]
I omitted the ^
and $
(beginning and end of string markers) because you said you'd have three-character strings, but there's no harm in including them, and they may improve speed, not that that'll be a big deal on such short input.
Of course, this assumes you're working in a language and locale where the uppercase equivalent of o
, n
, and d
are O
, N
, and D
. If not, you'll need to tell your regex interpreter to ignore case. The mechanism varies by language/framework.
For python, you'd use something like:
re.match('[1-9ond][123][0-9]', inputstring, re.IGNORECASE)
The re.match
forces a match at the beginning of string, so you wouldn't need the ^
in any case.
Upvotes: 5
Reputation: 755457
Slight variation on a few other answers. Restrict the input to be exactly the matched text.
^[1-9ondOND][123][0-9]$
Upvotes: 9
Reputation: 132494
In a PREG-based system (most of them these days):
^(?:[1-9]|[ond])[1-3][0-9]$
Some systems require the start/end markers (PHP, Perl, but not .NET for instance), if yours does, it'd end up something like:
/^(?:[1-9]|[ond])[1-3][0-9]$/
Upvotes: -2