I'm trying to set up a regular expression and I'm not getting it.
How do I set up a regular expression that accepts only numbers, slash, and hyphen?
I'm trying to set up a regular expression and I'm not getting it.
How do I set up a regular expression that accepts only numbers, slash, and hyphen?
This is the droid you are looking for:
/[\d\/-]+/
Some particularities of the list above:
\d
comprises all numbers \/
character represents a forward slash; if the regular expression delimiter were another one (for example, #
), it would not be necessary to escape Another way to mount this expression is by using a number range .
It looks like this:
[0-9\/-]+
Generally I like to mount using ranges ( 0-9
, A-Z
, a-z
, …
) instead of \d
because it gets more explicit.
Here you can see it working: link
I was somewhat in doubt about this issue.
Note that the regex suggested by Rodrigo selects (digit, bar, hyphen) but also the first digit OR the first digit OR the first digit ONLY (separately), whichever appears first. Example . I do not know if this is the desired result. But if it is, it would use the g
modifier to complement Rodrigo's solution. Example .
So he can match all parts of the text where he finds the searched string, more than once.
But if it is to accept uniquely and uniquely S, bar and hyphen, try this pattern (\d+\/-)+
. Example .