正则表达式:允许除某些选定字符外的所有字符 [英] Regex: allow everything but some selected characters

查看:756
本文介绍了正则表达式:允许除某些选定字符外的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证一个textarea,但是我没有得到正则表达式(花了我一天的时间和一堆教程来弄清楚它).

I would like to validate a textarea and I just don't get regex (It took me the day and a bunch of tutorials to figure it out).

基本上,我希望能够允许所有内容(包括换行符和战车),但可能是恶意字符(会导致安全漏洞的字符). 由于不允许使用的字符很少,因此我认为创建黑名单比白名单更有意义.

Basically I would like to be able to allow everything (line breaks and chariots included), but the characters that could be malicious( those which would lead to a security breach). As there are very few characters that are not allowed, I assume that it would make more sense to create a black list than a white one.

我的问题是:正则表达式中标准的除了什么"是什么?

My question is: what is the standard "everything but" in Regex?

我正在使用javascript和jquery.

I'm using javascript and jquery.

我尝试了此操作,但是它不起作用(我知道这很糟糕.):

I tried this but it doesn't work (it's awful, I know..):

var messageReg = /^[a-zA-Z0-9éèêëùüàâöïç\"\/\%\(\).'?!,@$#§-_ \n\r]+$/;

谢谢.

推荐答案

正如Esailija所说,这对于真正的安全性不会有任何作用.

As Esailija mentioned, this won't do anything for real security.

您提到的代码几乎是一个否定的集合,正如murgatroid99提到的,^放在括号内.因此,正则表达式将匹配该列表中未包含的任何内容.但是看来您确实想删除那些字符,因此您的正则表达式不需要取反.

The code you mentioned is almost a negated set, as murgatroid99 mentioned, the ^ goes inside the brackets. So the regular expression will match anything that is not in that list. But it looks like you really want to strip out those characters, so your regexp doesn't need to be negated.

您的代码应如下所示:

str.replace(/[a-zA-Z0-9éèêëùüàâöïç\"\/\%\(\).'?!,@$#-_ \n\r]/g, "");

也就是说,删除我正则表达式中的所有字符.

That says, remove all the characters in my regular expression.

但是,这就是说您不想保留a-zA-Z0-9,确定要删除这些内容吗?

However, that is saying you don't want to keep a-zA-Z0-9 are you sure you want to strip those out?

此外,chrome不喜欢正则表达式中的§,您必须使用\x以及字符的十六进制代码

Also, chrome doesn't like § in Regular Expressions, you have to use the \x along with the hex code for the character

这篇关于正则表达式:允许除某些选定字符外的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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