首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JS正则表达式获取没有特定后缀的字符串段

使用JS正则表达式获取没有特定后缀的字符串段
EN

Stack Overflow用户
提问于 2020-08-04 15:37:02
回答 2查看 55关注 0票数 0

我有个网址,可以是

代码语言:javascript
复制
https://arxiv.org/abs/2004.10934

或带有后缀v0-9。

代码语言:javascript
复制
https://arxiv.org/abs/2004.10934v3

我想用regex过滤掉v0-9部分。

也就是说,无论我们给哪种类型的url,都会得到https://arxiv.org/abs/2004.10934'

下面是我现在所拥有的,它很有效,但看起来很烦躁.

代码语言:javascript
复制
let url = 'https://arxiv.org/abs/2004.10934v3'
let regURL = /(.*(?<!v[0-9])(?<!v))/g;
let url_f = regURL.exec(url)[0];

有更好的正则表达式吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-04 18:52:51

使用

代码语言:javascript
复制
/^(.*?)(v\d+)?$/

证明

解释

代码语言:javascript
复制
NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  (                        group and capture to \2 (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    v                        'v'
--------------------------------------------------------------------------------
    \d+                      digits (0-9) (1 or more times (matching
                             the most amount possible))
--------------------------------------------------------------------------------
  )?                       end of \2 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \2)
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

JavaScript:

代码语言:javascript
复制
let url = 'https://arxiv.org/abs/2004.10934v3'
let regURL = /^(.*?)(v\d+)?$/;
let [_, url_f, version] = regURL.exec(url);
console.log(url_f);

票数 0
EN

Stack Overflow用户

发布于 2020-08-04 15:42:46

如果用空字符串替换v0-9,那么它将被过滤掉:

代码语言:javascript
复制
url.replace(/v[0-9]$/, '')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63250297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档