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!
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 /^[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 :-]+$/
您可以使用范围。
^[0 \-:]{1,}$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.