I have little to no experience in writing regular expressions. How would I go about checking that a string contains only zeros, spaces, hyphens, and colons? Thanks!
3 Answers
You should get good performance using a simple regex (no forward lookups):
^[0 :-]++$
Breaking it down:
^recognizes the beginning of the input[]means that any character within the brackets matches.+means that the preceding (the brackets) must match 1 or more times.++makes it possesive, improving performance.$recognizes the end of the input
6 Comments
riwalk
@AlixAxel, how do you figure? I've never seen a ++ operator before.
Jenny Shoars
Thanks. How does the regex distinguish between the hyphen being used as meaning between (like in "a-z") and being used as meaning itself?
Alix Axel
@JennyShoars: When it's at the start/end of the list
- is just another character.Jenny Shoars
Makes sense, but are there any other special characters that need this special position to be considered just the character that they are? And how do you resolve multiple of these then?
riwalk
@AlixAxel, ah! So
++ behaves exactly as + does in lex/flex. Learn something new every day |
/^[0\s:-]+$/
^= start of string[0\s:-]+= one or more zeros, spaces, hyphens, colon. The+means one or more,\sis any whitespace character, which may include line breaks and tabs.$= end of string
Since the pattern is anchored between ^ and $, no characters other than those in the [] character class will match.
If instead of any whitespace character, you permit only a literal space, use:
/^[0 :-]+$/