0
I’m trying to put together a regular expression and I’m not getting it.
How do I mount a regular expression that only accepts numbers, bar, and hyphen?
0
I’m trying to put together a regular expression and I’m not getting it.
How do I mount a regular expression that only accepts numbers, bar, and hyphen?
3
This is the droid you’re looking for:
/[\d\/-]+/
Some particularities of the above list:
\d
comprises all numbers\/
represents a bar; if the regular expression delimiter were another (for example, #
), it would not be necessary to escape2
Another way to assemble this expression is by using a crease number.
Stay that way:
[0-9\/-]+
Usually I like to ride using ranges (0-9
, A-Z
, a-z
, …
) instead of \d
because it gets more explicit.
Here you can see it working: https://regex101.com/r/uM3wC2/1
Does not work. Your pattern selects only numbers. https://regex101.com/r/uM3wC2/2
It does work. Add /g
which he will take globally: https://regex101.com/r/uM3wC2/3 That’s not what he asked for, but.
@zwitterion a regex is right: "numbers, bar and hyphen". Joining together g
as a flag then takes more than just the first.
i understood that it has to be numbers AND bar AND hyphen. AND not numbers OR bar OR hyphen. If it is OR your example is correct. You will select the first (and only the first) group ( as shown in the example https://regex101.com/r/uM3wC2/2 ). If you add g
will just pick up the other parts of the OR. But does not appear to be the requested.
@zwitterion he asked for a regular expression that accepted ONLY numbers, bar and hyphen, but did not specify which order or frequency. If you do not use the modifier /g
, will marry only those 3 in any order or frequency in a string
. If you use the /g
will marry N tokens
of a string. Note that this expression does not house spaces.
1
I was kind of wondering about that question.
Note that the regex suggested by Rodrigo selects (digit, bar, hyphen) but tbm the first digits OR the first bar OR the first hyphen ONLY (separately), whichever appears first. Example. I don’t know if this is the desired result. But if it is, I would use the modifier g
to complement Rodrigo’s solution. Example.
So he can match it in every part of the text where he finds the string sought, more than once.
But if it is to accept single and exclusively digits, bar and hyphen, try this pattern (\d+\/-)+
. Example.
Browser other questions tagged regex
You are not signed in. Login or sign up in order to post.
If you use the delimiter
/
must escape a/
that is for capture, if contrary will generate error, as it will be interpreted as final delimiter. Solution change the delimiter, if the language allows, escape to/
.– Guilherme Lautert
That’s right, I’ll change the answer.
– Rodrigo Rigotti
@Rodrigorigotti can escape the hyphen too. So it’s safe if the AP uses in another order.
– Sergio