我有个网址,可以是
https://arxiv.org/abs/2004.10934或带有后缀v0-9。
https://arxiv.org/abs/2004.10934v3我想用regex过滤掉v0-9部分。
也就是说,无论我们给哪种类型的url,都会得到https://arxiv.org/abs/2004.10934'。
下面是我现在所拥有的,它很有效,但看起来很烦躁.
let url = 'https://arxiv.org/abs/2004.10934v3'
let regURL = /(.*(?<!v[0-9])(?<!v))/g;
let url_f = regURL.exec(url)[0];有更好的正则表达式吗?
发布于 2020-08-04 18:52:51
使用
/^(.*?)(v\d+)?$/见证明。
解释
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
stringJavaScript:
let url = 'https://arxiv.org/abs/2004.10934v3'
let regURL = /^(.*?)(v\d+)?$/;
let [_, url_f, version] = regURL.exec(url);
console.log(url_f);
发布于 2020-08-04 15:42:46
如果用空字符串替换v0-9,那么它将被过滤掉:
url.replace(/v[0-9]$/, '')https://stackoverflow.com/questions/63250297
复制相似问题