[英]How to properly escape a single quote?
I have the following regex to validate email addresses: 我使用以下正则表达式来验证电子邮件地址:
var content = /^([\w._+-]|(<?))+[a-zA-Z0-9]@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9\_]+\.)+[a-zA-Z0-9-_.]{1,}))$/;
I need to allow for '
before the @ symbol, so per this SO answer I updated my regex to be such: 我需要在@符号前允许
'
,所以根据这个答案,我将正则表达式更新为:
var content = /^([\w._+-/\']|(<?))+[a-zA-Z0-9]@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9\_]+\.)+[a-zA-Z0-9-_.]{1,}))$/;
Note the addition of /\\'
to the first capture block. 注意在第一个捕获块中添加了
/\\'
。
However, I'm now able to save data with a /
in it when that should not be allowed. 但是,我现在可以在不应该包含
/
保存数据。 If I try simply just adding a '
to the capture block, this throws an 'invalid regex' error. 如果我只是尝试在捕获块中添加一个
'
,则会抛出'无效的正则表达式'错误。
How do you escape a single quote character without allowing forward slashes? 如何在不使用正斜杠的情况下转义单引号字符?
Edit: For the discussion in the comments, here is a screenshot: 编辑:对于评论中的讨论,这是一个屏幕截图:
The first is Visual Studio error 第一个是Visual Studio错误
The second is the line in the Chrome debugger 第二是Chrome调试器中的这一行
The third is the exception that gets thrown when I step over the creation of the regex. 第三个是我跨过正则表达式创建时抛出的异常。
You do not need to escape the single quote inside a regex literal. 您无需在正则表达式文字中转义单引号。
The issue in your case is the -
that ends your character class. 您遇到的问题是
-
结束您的角色类。 If it is positioned at the end, it serves as a literal -
while it opens a range when used in between two characters. 如果将其放置在末尾,则它用作文字
-
在两个字符之间使用时会打开一个范围。
Your current attempt opens that range between +
and /
, including ,
and -
. 您当前试图打开之间的范围
+
和/
,其中包括,
和-
If you directly use the '
, the range is invalid, as '
has a lower index than +
. 如果直接使用
'
,则范围无效,因为'
索引比+
低。
To solve this, either escape the minus \\-
or move it to the end again. 要解决此问题,请转义减号
\\-
或再次将其移至末尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.