如何在正则表达式中转义斜杠? [英] How to escape slashes in regex?

查看:98
本文介绍了如何在正则表达式中转义斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一些正则表达式来测试 YouTube 嵌入的视频:

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

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

它适用于我测试时的预期,但问题是我需要将该正则表达式作为字符串传递给某个函数.特别是我使用 htmlawed,我将以下字符串传递给函数:

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?

推荐答案

如果您有一个字符串,则需要对字符串文字的反斜杠(和引号)进行转义.或者,根据函数如何从字符串构建正则表达式,您可能根本不需要转义斜杠(我不这么认为).

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\\\\]+$/\")"

这篇关于如何在正则表达式中转义斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆