How to escape asterisk in regexp?

后端 未结 2 1719
傲寒
傲寒 2020-12-30 23:28

I want to use the pattern *1*. I have tried \\*1\\*, but it doesn\'t work. Where is the problem?

相关标签:
2条回答
  • 2020-12-31 00:24

    need to use a backslash \ as the escape character in regexes.

    0 讨论(0)
  • 2020-12-31 00:25

    You have to escape it with a backslash:

    /\*1\*/
    

    Otherwise, an unescaped * in a RegExp will mean: Match 0 or more of the Preceding Character Group.

    Update:

    If you use the RegExp constructor, do it this way:

    new RegExp("\\*1\\*")
    

    You have to double-escape the backslashes because they need to be escaped in the string itself.

    0 讨论(0)
提交回复
热议问题