【问题标题】:regex to remove digits, allow only lowercase letters, remove special characters [closed]正则表达式删除数字,只允许小写字母,删除特殊字符[关闭]
【发布时间】:2018-05-10 12:13:04
【问题描述】:

这是我的代码:

private void txtMot_KeyUp(object sender, KeyEventArgs e)
{

    /* Clear message */
    txtMessage.Clear();


    Regex regex = new Regex(@"\d+");
    Match match = regex.Match(txtMot.Text);

    if (match.Success)
    {
        /* Text in red*/
        txtMessage.Foreground = Brushes.Red;
        /* Message text*/
        txtMessage.Text = "Only letters";
    }
}

我设法删除了所有数字。 我现在想知道,我怎样才能做到:

  • 删除数字。

  • 只允许小写字母。

  • 删除任何类型的特殊字符(_+ù$é)

请问我该怎么做?

【问题讨论】:

  • 呃,呃,[a-z]?

标签: c# regex wpf


【解决方案1】:

您可以简单地使用正则表达式 [a-z] 并使用不同的数据集进行测试,因为它只接受 lowercase letters

public static void Main()
{
    string test = "_+ù$é";   //change this to any set of test data
    Regex regex = new Regex(@"[a-z]");
    Match match = regex.Match(test);

    if (match.Success)
    {
      Console.WriteLine("Matched");
    }
    else
      Console.WriteLine("Not Matched");

}

dotNetFiddle

编辑:

上述 sn-p 在以下情况下会失败;

string test = "_+ù$é abc";

^ 因为它包含特殊字母和小写字母,如果您只想接受小写字母,那么;

替换这个:

Regex regex = new Regex(@"[a-z]");

使用这种模式:

Regex regex = new Regex(@"^([a-z]{1,25})$"); //this makes sure the string 
                                            // is only of lowercase 
                                           // letters and does not contain any digits
                                          // or special chars

dotNetFiddle

【讨论】:

  • 哦,确实谢谢你,它有效!我有一个空白,忘记了怎么做。谢谢
猜你喜欢
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多