How can I write a regex that match this
123/456
123/456/?
but not this
123/456/
I want on the second / it must be followed by a ?.
For Example I would like it to match this
'123/456'.match(X) // return ['123/456']
'123/456/?'.match(X) // return ['123/456/?']
'123/456/'.match(X) // return null
Update
I missed to say one important thing. It must not end with '?', a string like '123/456/?hi' should also match
The set of regular expressions is defined by the following rules. Every letter of ∑ can be made into a regular expression, null string, ∈ itself is a regular expression. If r1 and r2 are regular expressions, then (r1), r1. r2, r1+r2, r1*, r1+ are also regular expressions.
*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string.
Chaining regular expressions Regular expressions can be chained together using the pipe character (|). This allows for multiple search options to be acceptable in a single regex string.
By default, regular expressions will match any part of a string. It's often useful to anchor the regular expression so that it matches from the start or end of the string: ^ matches the start of string. $ matches the end of the string.
You can try this regex: \d{3}/\d{3}(/\?.*)?
It will match
/
/?any_text
(e.g. /?hi
) (optional)This example uses regular expression anchors like ^
and $
, but they are not required if you only try to match against the target string.
var result = '123/456/?hi'.match(/\d{3}\/\d{3}(\/\?.*)?/);
if (result) {
document.write(result[0]);
}
else {
document.write('no match');
}
This regular expression will work /^\d{3}\/\d{3}(\/\?.*)?/
See this JSFiddle.
Note: if you think it should match any number of digits then use \d+
instead of \d{3}
. The later matches exactly 3 digits.
Here you are:
[0-9]+/[0-9]+(/\?[^ ]*)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With