JavaScript RegExp:匹配,但不捕获(JavaScript RegExp: match, but don't capture)
SO上有一千个正则表达式问题,所以我很抱歉如果这已经被覆盖了。 我确实首先看。
鉴于以下模式:
(?:/|-)[0-9]{2}$以下字符串:
str1 = '65/65/65' str2 = '65/65/6565'比赛是:
str1 = '/65' // expected '65' str2 = '' // as I expected我的意图是:匹配,但不包括a /或- 。 什么是正确的正则表达式来满足我的期望?
There are a thousand regular expression questions on SO, so I apologize if this is already covered. I did look first.
Given the following pattern:
(?:/|-)[0-9]{2}$And the following strings:
str1 = '65/65/65' str2 = '65/65/6565'The matches are:
str1 = '/65' // expected '65' str2 = '' // as I expectedMy intention with ?: was to match, but not include a / or -. What is the correct regular expression to meet my expectations?
最满意答案
由于Javascript中没有可用的后视图,只需将所需的部分包装到捕获组中即可 :
var str = '65/66/67'; if(res = str.match(/(?:\/|-)([0-9]{2})$/)) { console.log(res[1]); }看小提琴
注意: (?:\/|-)可以用@anubhava评论的字符类 [\/-]替换。
As there's no lookbehind available in Javascript, just wrap the desired part into a capturing group:
var str = '65/66/67'; if(res = str.match(/(?:\/|-)([0-9]{2})$/)) { console.log(res[1]); }See fiddle
Note: (?:\/|-) can be replaced with a character class [\/-] like @anubhava commented.
更多推荐
发布评论