我需要在正则表达式中逃脱破折号吗? [英] Do I need to escape dash character in regex?
问题描述
我正在尝试理解短划线字符 -
需要使用正则表达式中的反斜杠进行转义吗?
I'm trying to understand dash character -
needs to escape using backslash in regex?
考虑这一点:
var url = '/user/1234-username';
var pattern = /\/(\d+)\-/;
var match = pattern.exec(url);
var id = match[1]; // 1234
正如您在上面的正则表达式中所看到的,我正在尝试提取id的数量来自网址。我还使用反斜杠 \
在我的正则表达式中转义 -
字符。但是当我删除那个反斜杠时,仍然很好....换句话说,这两个都很好:
As you see in the above regex, I'm trying to extract the number of id from the url. Also I escaped -
character in my regex using backslash \
. But when I remove that backslash, still all fine ....! In other word, both of these are fine:
/\/(\d+)\-/
/\/(\d+)-/
现在我想知道哪一个是正确的(标准)?我需要在正则表达式中逃脱破折号吗?
Now I want to know, which one is correct (standard)? Do I need to escape dash character in regex?
推荐答案
如果它可以被解释为范围指示器,你只需要转义破折号字符(里面可以是这种情况) 角色类)。
You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).
/-/ # matches "-"
/[a-z]/ # matches any letter in the range between ASCII a and ASCII z
/[a\-z]/ # matches "a", "-" or "z"
/[a-]/ # matches "a" or "-"
/[-z]/ # matches "-" or "z"
这篇关于我需要在正则表达式中逃脱破折号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!