我需要在正则表达式中逃脱破折号吗?

编程入门 行业动态 更新时间:2024-10-19 07:33:05
本文介绍了我需要在正则表达式中逃脱破折号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试理解短划线字符 - 需要使用正则表达式中的反斜杠进行转义吗?

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"

更多推荐

我需要在正则表达式中逃脱破折号吗?

本文发布于:2023-08-02 11:38:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1277493.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:破折号   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!