[英]simple javascript regex to match url pattern help needed
I've never been good with regex syntax, can someone help me out to to check if a URL matches a specific structure in my example? 我从未使用过正则表达式语法,有人可以帮我检查一下示例中的URL是否匹配特定的结构吗?
The .* can be anything including /-_# etc, the 0-9 would be any number length (ex 1993334). 。*可以是任何东西,包括/ -_#等,0-9可以是任何数字长度(例如1993334)。
var pattern = new RegExp('/articles/[0-9]/[.*]');
if (pattern.test(document.location.href)) {
// match found
}
Try this: 尝试这个:
\/articles\/[0-9]+\/.*
So, escape the slashes, and use +
to specify there has to be "one or more" of the preceding element. 因此,请转义斜线,并使用
+
来指定前面的元素必须为“一个或多个”。
Use [0-9]+ instead of [0-9] and use the slashes correctly.. 使用[0-9] +代替[0-9],并正确使用斜线。
var pattern = new RegExp(\/articles\/[0-9]+\/(.*));
if (pattern.test(document.location.href)) {
// match found
}
You've already gotten your answer, so that's no problem, but just like Cerbrus told you, I'll explain why the regex didn't work. 您已经得到了答案,所以这没问题,但是就像Cerbrus告诉您的那样,我将解释为什么正则表达式不起作用。
new RegExp('/articles/[0-9]/[.*]');
The /articles/
part is completely correct. /articles/
部分完全正确。
You've had an idea about the [0-9]
(any digit), but you've specified that "this appears only once". 您已经对
[0-9]
(任意数字)有所了解,但是您已指定“仅出现一次”。 By adding a +
you specify "one or more", just like if you added a *
it'd mean "zero or more". 通过添加
+
您可以指定“一个或多个”,就像添加了*
,表示“零或多个”。
In your last match [.*]
, you're matching "any character" ( .
) repeated "zero or more" ( *
) times, and therefore an URL of /articles/2/
(without anything after this) could be matched, and I assume this is unwanted behaviour. 在您的上一个匹配项
[.*]
,您要匹配重复了“零个或多个”( *
)次的“任何字符”( .
),因此可以匹配/articles/2/
的URL(此后没有任何内容) ,并且我认为这是不必要的行为。
To be completely precise, you might even use a regex of 确切地说,您甚至可以使用的正则表达式
^/articles/[0-9]+/.+$
Whereas the ^
means "this has to be the start" and $
meaning "this has to be the end". 而
^
表示“这必须是开始”,而$
表示“这必须是结束”。
If you don't include these, an URL like /non-relevant-url/articles/123/my-article/whatever/foo/bar
could be matched (and you might not want to match if it starts with /non-relevant-url
- the ^
fixes this.) 如果您不包括这些内容,则可以匹配
/non-relevant-url/articles/123/my-article/whatever/foo/bar
类的URL(如果以/non-relevant-url
开头,则可能不希望进行匹配/non-relevant-url
^
解决了这个问题。)
Note: The $
isn't really necessary in this example, seeing as you end it with a "match everything past this point", but I included it so you'd know what it means (as it's just as useful to know as ^
) 注意:在此示例中,实际上并不需要
$
,因为您在结束时会看到“匹配此点之后的所有内容”,但是我包括了它,因此您会知道它的含义(因为与^
一样有用)
Hope it gave you a tiny insight in regex, which once learned is incredibly powerful. 希望它为您提供了对正则表达式的细微了解,而正则表达式一经学习便具有强大的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.