正则表达式允许一组字符并禁止其他字符 [英] Regular expression to allow a set of characters and disallow others

查看:218
本文介绍了正则表达式允许一组字符并禁止其他字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想限制用户在字段中输入以下特殊字符:

I want to restrict the users from entering the below special characters in a field:


œçşÇŞ
ğĞščřŠŘŇĚŽĎŤČňěž
ůŮ
İťı
—¿„"*@
Newline
Carriage return

还有一些将被添加到此列表中,但我最终将拥有完整的限制列表。

A few more will be added to this list but I will have the complete restricted list eventually.

但是他可以输入某些外国字符,例如äöüÄÖÜÿï等除了字母数字字符,通常的特殊字符等。

But he can enter certain foreign characters like äöüÄÖÜÿï etc in addition to alphanumeric chars, usual special chars etc.

是否有一种简单的方法来构建正则表达式来执行此操作。在不允许的列表中添加如此多的字符,如

Is there an easy way to build a regex for doing this. Adding so many chars in the not allowed list like


[^œçşÇŞ ğĞščřŠŘŇĚŽĎŤČňěž ůŮ İ ť ı — ¿ „ " * @]+

似乎不起作用。

我没有完整的清单允许的字符。即使我试图获得它也会太长,并且会包括所有字符:

And I do not have the complete list of allowed characters. It would be too long even if I try to get it and would include all chars like:


~`!#$%^&()[]{};':",.

以及某些外国字符。

推荐答案

您可以使用正则表达式,但为什么不检查您的字符串中是否有任何不允许的字符使用内置方法?例如,在.NET中你可以使用的世界.Contains()。

You COULD use a regular expression for this, but why not just check if any of the disallowed characters are in your string with a builtin method? For example, in the .NET world you could use .Contains().

就个人而言,我会创建一个允许的字符列表,然后检查你的字符串是否没有任何字符在你的列表中。使用白名单也可以确保你没有忘记任何坏字符。

Personally, I would create a list of allowed characters, then just check that your string doesn't have any characters that aren't in your list. Using a whitelist will ensure that you haven't forgotten any "bad" characters as well.

这篇关于正则表达式允许一组字符并禁止其他字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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