最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regular Expression - followed by - Stack Overflow

programmeradmin0浏览0评论

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
Add a comment  | 

5 Answers 5

Reset to default 7

You 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

发布评论

评论列表(0)

  1. 暂无评论