简体   繁体   English

如何验证字符串仅包含某些字符

[英]How to validate that a string contains only certain characters

I am working on an assignment for school: 我正在为学校做作业:

I have passed a string to a mutator and I need to validate that it only contains spaces, hyphens or upper and lower case letters. 我已经将一个字符串传递给了mutator,我需要验证它仅包含空格,连字符或大小写字母。

The output is always " ". 输出始终为“”。

Can you see what I am doing wrong? 你能看到我做错了吗? Is there a smarter way to do this? 有更聪明的方法吗? I got this way from my instructor but its not working. 我从我的老师那里得到了这种方式,但是它不起作用。 Here is my code: 这是我的代码:

public void setFirstName(string newFirstName

{

    bool valid;

    valid = System.Text.RegularExpressions.Regex.IsMatch(newFirstName, "^[- a-zA-Z]?$");

    if (valid)

    {

        firstName = newFirstName;

    }

        firstName = " ";

}

You need else block. 您需要其他阻止。

public void setFirstName(string newFirstName)
{
    bool valid;
    valid = System.Text.RegularExpressions.Regex.IsMatch(newFirstName, "^[- a-zA-Z]*$");
    if (valid)
    {
        firstName = newFirstName;
    }
    else
    {
        firstName = " ";
    }
}

Update 更新资料

Your regex seems also wrong it needs * for zero or more occurance instead of ?. 您的正则表达式似乎也错了,它需要*零个或多个出现而不是?。 Correct regex => ^[- a-zA-Z]*$ 正确的正则表达式 => ^[- a-zA-Z]*$

Click here to see working fiddle => link 点击这里查看工作提琴=> 链接

As an alternative to RegEx (which I would not recommend if you're still just learning C#), you can use basic string validation with LINQ and the built in .Net char methods . 作为RegEx的替代方法(如果您仍在学习C#,我不建议这样做),可以将基本的字符串验证与LINQ和内置的.Net char方法一起使用

bool isValid = newFirstName.All(x => char.IsLetter(x) || x == '-' || x == ' ');

In this particular case, All will check that every element in the array (a string is a char array) matches the predicate provided where every character: 在这种特殊情况下, All将检查数组中的每个元素(字符串是char数组)是否与提供的谓词与每个字符相匹配:

  • must be a letter (upper or lower) OR 必须是字母(大写或小写)或
  • must be a dash '-' OR 必须为破折号“-”或
  • must be a space ' ' 必须是一个空格''

If anyone of those conditions fail, then the result will be false. 如果这些条件中的任何一个失败,那么结果将为假。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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