在 JavaScript 正则表达式中使用 {1}+ 占有量词时的正则表达式 eError [英] Regex eError when using {1}+ possessive quantifier in JavaScript regex

查看:45
本文介绍了在 JavaScript 正则表达式中使用 {1}+ 占有量词时的正则表达式 eError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我同时学习 Javascript 和 Express.js,所以我在发出 get 请求时尝试使用正则表达式

Since I am learning Javascript and Express.js at the same time I was experimenting around with regular expressions when making a get request

为了熟悉正则表达式,我使用了这个图表(也在下面转载)

To familiaries my self with regular expressions I used this chart (also reproduced below)

Greedy  Reluctant   Possessive  Meaning
X?      X??         X?+         X, once or not at all
X*      X*?         X*+         X, zero or more times
X+      X+?         X++         X, one or more times
X{n}    X{n}?       X{n}+       X, exactly n times
X{n,}   X{n,}?      X{n,}+      X, at least n times
X{n,m}  X{n,m}?     X{n,m}+     X, at least n but not more than m times

我的问题是,如果一个 url 只有一个 /,我怎么能得到一个正则表达式来匹配它.
换句话说,它只会匹配默认的 url localhost:1337/

My question is that how can I get a regex to match a url if it only has one /.
In other words, it would only match the default url localhost:1337/

app.get(//{1}/, function (req, res) {
    res.render("index"); 
});

然而,我上面的当前正则表达式匹配其他路径名(即localhost:1337/home/login),因为现在我知道它使用贪婪量词

However, my current regex above matches other pathnames(ie. localhost:1337/home/login) because now I know it uses the greedy quantifier

阅读更多关于正则表达式的内容后,我改变了量词,使其具有所有格.
//{1}+/

After reading more on regular expressions, I changed the quantifier so its possessive.
//{1}+/

但是后来快递报了这个错误:

But then express gave this error:

Syntax Error: Invalid Regular Expression: //{1}+/: Nothing to Repeat

那么我的正则表达式语法有错吗?

So is my syntax for the regular expression wrong?

推荐答案

JavaScript 不支持所有格量​​词.您看到的错误是因为 + 只能用作贪婪的一个或多个量词.

JavaScript does not support possessive quantifiers. The error you are seeing occurs because the + can only be used as a greedy one-or-more quantifier.

您引用的图表来自 Oracle,并解释了 Java(而非 JavaScript)支持的量词.

The chart you reference is from Oracle, and is explaining the quantifiers supported by Java, not JavaScript.

您不需要采取任何特殊措施来进行您想要的匹配.

You don't need to resort to anything special to do the kind of matching you want.

如果你想匹配一个以/结尾的字符串,其中没有其他斜线,你可以使用:

If you want to match "a string ending in a /, with no other slashes in it, you can use:

/^[^/]+/$/

字符串的开头,一个或多个非斜杠,后跟一个斜杠,后跟字符串的结尾.

Start of string, one or more non-slashes, followed by a slash, followed by the end of the string.

这篇关于在 JavaScript 正则表达式中使用 {1}+ 占有量词时的正则表达式 eError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆