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
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
Share Improve this question edited Apr 24, 2012 at 7:14 Codler asked Apr 24, 2012 at 6:56 CodlerCodler 11.3k6 gold badges54 silver badges66 bronze badges 2- 1 Could the numbers be different than 123 and 456? If yes, how long can they be? – sp00m Commented Apr 24, 2012 at 7:19
- @sp00m, yes, it can be any digits – Codler Commented Apr 24, 2012 at 7:20
5 Answers
Reset to default 7You can try this regex: \d{3}/\d{3}(/\?.*)?
It will match
- 3 digits
- followed by a
/
- followed by 3 digits
- followed by
/?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]+(/\?[^ ]*)?
What other rules do you have?
If you want to accept all strings with last character other than ?
, use "[^?]$"
If you want to accept strings that start with 123/456
and optionally end with /?
, use "^123/456(/\?)?$"
I think this should work:
'123/456'.match(/^123\/456(\/\?)?$/) // returns ["123/456", undefined]
'123/456/'.match(/^123\/456(\/\?)?$/) // returns null
'123/456/?'.match(/^123\/456(\/\?)?$/) // returns ["123/456/?", "/?"]
EDIT: added the other cases