1

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!

0

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

6 Comments

@AlixAxel, how do you figure? I've never seen a ++ operator before.
Thanks. How does the regex distinguish between the hyphen being used as meaning between (like in "a-z") and being used as meaning itself?
@JennyShoars: When it's at the start/end of the list - is just another character.
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?
@AlixAxel, ah! So ++ behaves exactly as + does in lex/flex. Learn something new every day
|
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 :-]+$/ 

Comments

1

You can use a range.

^[0 \-:]{1,}$

2 Comments

{1,} is the same as +. Also, you wouldn't need to escape - if you placed it at the beginning or ending of the list.
true but you should know what characters you need to escape.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.