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!
Asked
Active
Viewed 1,581 times
3 Answers
3
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

riwalk
- 14,033
- 6
- 51
- 68
-
@AlixAxel, how do you figure? I've never seen a ++ operator before. – riwalk Oct 11 '12 at 19:29
-
Thanks. How does the regex distinguish between the hyphen being used as meaning between (like in "a-z") and being used as meaning itself? – Jenny Shoars Oct 11 '12 at 19:31
-
@JennyShoars: When it's at the start/end of the list `-` is just another character. – Alix Axel Oct 11 '12 at 19:32
-
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? – Jenny Shoars Oct 11 '12 at 19:33
-
1@AlixAxel, ah! So `++` behaves exactly as `+` does in lex/flex. Learn something new every day – riwalk Oct 11 '12 at 19:36
-
@Yup, there are a few. I suggest you read this: http://www.regular-expressions.info/charclass.html. – Alix Axel Oct 11 '12 at 19:37
3
/^[0\s:-]+$/
^
= start of string[0\s:-]+
= one or more zeros, spaces, hyphens, colon. The+
means one or more,\s
is 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 :-]+$/

Michael Berkowski
- 267,341
- 46
- 444
- 390
1
You can use a range.
^[0 \-:]{1,}$

Rayshawn
- 2,603
- 3
- 27
- 46
-
`{1,}` is the same as `+`. Also, you wouldn't need to escape `-` if you placed it at the beginning or ending of the list. – Alix Axel Oct 11 '12 at 19:22
-