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

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

问题描述

由于我正在学习Javascript和Express.js,同时我在制作获取请求时正在尝试使用正则表达式

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

我的问题是如果只有一个 / ,我如何获得正则表达式来匹配网址。

换句话说,它只匹配默认网址 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:

/[^/]+\/$/

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

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

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

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