简体   繁体   中英

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

The second is the line in the Chrome debugger

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM