duanou3868 2012-08-04 16:36
浏览 43
已采纳

如何逃避正则表达式中的斜杠?

I've made some regex to test for a YouTube embedded video:

/^(http:\/\/www\.youtube\.com\/embed\/)[^\/\s\\]+$/

It works for what I expect when I test it, but the problem though is that I need to pass that regex as a string to some function. Particularly I'm using htmlawed, where I pass a following string to a function:

func('iframe=-*,src(match="/^(http:\/\/www\.youtube\.com\/embed\/)[^\/\s\\]+$/")');

The problem is that the above regex sort of works, but it just ignores the slashes, and accepts anything in place of them.

That is why I suspect that there is a problem with escaping.

I would appreciate if you could advice some alternative ways of escaping these slashes and backslashes... there must be some way?

  • 写回答

2条回答 默认 最新

  • drfu29983 2012-08-04 16:40
    关注

    If you have a string, you will need to escape the backslashes (and quotes) for the string literal. Or, depending on how the function builds the regex from the string, you might not need to escape slashes at all (I don't think so here).

    "iframe=-*,src(match=\"/^(http:\\/\\/www\\.youtube\\.com\\/embed\\/)[^\\/\\s\\\\]+$/\")"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料