本文介绍了我需要在正则表达式中逃脱破折号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试理解短划线字符 -
需要使用正则表达式中的反斜杠进行转义吗?
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:
- )。
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"
这篇关于我需要在正则表达式中逃脱破折号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!