JavaScript RegExp:匹配,但不捕获(JavaScript RegExp: match, but don't capture)

编程入门 行业动态 更新时间:2024-10-26 01:25:37
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 expected

My 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.

更多推荐

本文发布于:2023-07-31 00:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340442.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:但不   RegExp   JavaScript   match   capture

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!