【问题标题】:normalizing input string before searching through List c#在通过 List c# 搜索之前规范化输入字符串
【发布时间】:2017-12-24 16:23:32
【问题描述】:

我正在创建一个多表单应用程序,该应用程序在用户保存表单之前进行了一系列验证测试。其中一个验证功能需要评估用户是否输入了某些关键字,例如“Unkown”、“TBA”、“N/A”。我需要首先规范化输入字符串,以去除所有不需要的字符,例如空格,以及额外的大小写,例如“UNkown”、“tBA”。然后需要对照我的list 进行检查。

这是我当前的方法,但是我的正则表达式没有正确规范化我的输入字符串,如果单词前面有空格,则会通过验证

public bool useUnkownEntity(string strTest)
{  
    Regex rgx = new Regex(@"^[a-zA-Z]");


    List<string> unkown = new List<string> { "Unkown", "tba", "tbc","N/a"};
    useUnkownEntity(rgx.Replace(strTest, ""));

    if (unkown.Contains(strTest, StringComparer.OrdinalIgnoreCase))
    {
        MessageBox.Show("please refre to the unkown ENtity within");
        return false;
    }
    return true;

}

如果找到任何想要的单词,无论它们是否不完全匹配,我想要的结果都是错误的。最好的方法是捕捉用户可能输入的所有可能性以通过验证。

这是我调用方法的事件

private void txt_SurName_Validating(object sender, CancelEventArgs e)
        {   // Convert User input to TitleCase
            if (useUnkownEntity(txt_SurName.Text))
            {
                return; 

            }
            if (string.IsNullOrWhiteSpace(txt_SurName.Text))
            {
                epSurname.Clear(); _IsValid = true;
            }

            else if (util.IsAllLetters(txt_SurName.Text))
            {
                epSurname.Clear(); txt_SurName.Text = util.ToTitle(txt_SurName.Text); _IsValid = true;
            }

            else
            {
                epSurname.SetError(txt_SurName, "InValid Surname"); _IsValid = false;
            }

        }

【问题讨论】:

  • 也许你想写 new Regex(@"[^a-zA-Z]") 来匹配除 ASCII 字母之外的任何字符。
  • 我试过了,但是现在它给了我一个空执行
  • 而且副本上的答案也不是我需要的,我需要允许诸如 N/A 之类的符号
  • 重新制定你需要的,不清楚你需要什么。您是否尝试修改strTest?那为什么要使用useUnkownEntity(rgx.Replace(strTest, ""));?我想应该是strTest = rgx.Replace(strTest, "");
  • 你的方法似乎是递归的——没有退出递归——你能显示你的真实代码吗?

标签: c# .net regex winforms


【解决方案1】:

到目前为止,这是我的答案,它忽略大小写而不是空格,如果我在单词的开头输入几个空格,它将失败,就像在 N/A 上忘记 / 时一样。

 public bool useUnkownEntity(string strTest)
        {
            Regex rgx = new Regex("[^a-zA-Z/s/ ]");
            List<string> unkown = new List<string> { "Unkown", "tba", "tbc","N/A"};
              strTest = rgx.Replace(strTest, "");
            if (unkown.Contains(strTest, StringComparer.OrdinalIgnoreCase))
            {
                MessageBox.Show("Please refer to the unkown Entity within!!");
                return false;
            }
            return true;

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 2011-06-20
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多