C# 中不允许检查特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13062911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:31:54  来源:igfitidea点击:

Check for special characters are not allowed in C#

c#regex

提问by ankur

I have to validate a text box from a list of special characters that are not allowed. This all are not allowed characters.

我必须从不允许的特殊字符列表中验证文本框。这都是不允许的字符。

"&";"\";"/";"!";"%";"#";"^";"(";")";"?";"|";"~";"+";" ";
                                                   "{";"}";"*";",";"[";"]";"$";";";":";"=";"

Where semi-column is used to just separate between characters .I tried to write a regex for some characters to validate if it had worked i would extend it.it is not working . What I am doing wrong in this.

半列仅用于分隔字符。我尝试为某些字符编写正则表达式以验证它是否有效,我会扩展它。它不起作用。我在这方面做错了什么。

Regex.IsMatch(textBox1.Text, @"^[\%\/\\&\?\,\'\;\:\!\-]+$")

采纳答案by John Dvorak

^[\%\/\\&\?\,\'\;\:\!\-]+$

matches the strings that consist entirelyof special characters. You need to invert the character class to match the strings that do notcontain a special character:

匹配完全由特殊字符组成的字符串。您需要反转字符类以匹配包含特殊字符的字符串:

^[^\%\/\\&\?\,\'\;\:\!\-]+$
  ^--- added

Alternatively, you can use this regex to match any string containing onlyalphanumeric characters, hyphens, underscores and apostrophes.

或者,您可以使用此正则表达式匹配任何包含字母数字字符、连字符、下划线和撇号的字符串。

^[a-zA-Z0-9\-'_]$

The regex you mention in the comments

您在评论中提到的正则表达式

[^a-zA-Z0-9-'_]

matches a string that contains any character except those that are allowed (you might need to escape the hyphen, though). This works as well, assuming you reverse the condition correctly (accept the strings that do notmatch).

匹配包含除允许字符以外的任何字符的字符串(不过,您可能需要对连字符进行转义)。这也适用,假设您正确反转条件(接受匹配的字符串)。

回答by Alexei Levenkov

Your RegExp is "string consiting only of special characters (since you have begin/end markers ^and $).

您的 RegExp 是“仅由特殊字符组成的字符串(因为您有开始/结束标记^$)。

You probably want just check if string does not contain any of the characters @"[\%\/\\\&\?\,\'\;\:\!\-]")would be enough.

您可能只想检查字符串是否不包含任何字符@"[\%\/\\\&\?\,\'\;\:\!\-]")就足够了。

Also String.IndexOfAnymay be better fit if you just need to see if any of the characters is present in the source string.

String.IndexOfAny可能会更适合,如果你只需要看看是否有任何字符的存在源的字符串中。

回答by maximpa

You needed to remove ^from the beginning and $from the end of the pattern, otherwise in order to match the string should start and end with the special characters.

您需要从模式的开头删除^并从模式的末尾删除$,否则为了匹配字符串应该以特殊字符开头和结尾。

So, instead of

所以,而不是

@"^[\%\/\\&\?\,\'\;\:\!\-]+$"

it should be

它应该是

@"[\%\/\\&\?\,\'\;\:\!\-]+"

You can read more about start of string and end of string anchors here

您可以在此处阅读有关字符串开头和字符串结尾的更多信息

回答by Richard

If you are just looking for any of a list of characters then a regular expression is the more complicated option. String.IndexOfAnywill return the first index of any of an array of characters or -1. So the check:

如果您只是在寻找任何字符列表,那么正则表达式是更复杂的选项。String.IndexOfAny将返回任何字符数组的第一个索引或 -1。所以检查:

if (input.IndexOfAny(theCharacetrers) != -1) {
  // Found one of them.
}

where theCharacetrershas previously been set up at class scope:

其中,theCharacetrers先前已经设置了在类范围:

private readonly char[] theCharacetrers = new [] {'&','\','/','!','%','#','^',... };

回答by Sharafu

PLease use this in textchange event

请在 textchange 事件中使用它

        //Regex regex = new Regex("([a-zA-Z0-9 ._@]+)");
        Regex regex = new Regex("^[a-zA-Z0-9_@(+).,-]+$");
        string alltxt = txtOthers.Text;//txtOthers is textboxes name;
        int k = alltxt.Length;
        for (int i = 0; i <= k - 1; i++)
        {

            string lastch = alltxt.Substring(i, 1);
            MatchCollection matches = regex.Matches(lastch);
            if (matches.Count > 0)
            {

            }
            else
            {

                txtOthers.Text = alltxt.Remove(i, 1);

                i = i - 1;
                alltxt = txtOthers.Text;
                k = alltxt.Length;
            }
            txtOthers.Select(txtOthers.TextLength, 0);
        }

BY Sharafu Hameed

莎拉夫·哈米德