我正在尝试理解短划线字符 - 需要使用正则表达式中的反斜杠进行转义吗?
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 +) - /
- /\/(\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"更多推荐
我需要在正则表达式中逃脱破折号吗?
发布评论