C#正则表达式:检查" A-Z"和" A-Z" [英] C# Regex: Checking for "a-z" and "A-Z"

查看:264
本文介绍了C#正则表达式:检查" A-Z"和" A-Z"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查,如果一个字符串a-z或A-Z之间的字符输入。不知怎的,我的正常前pression似乎并没有把它捡起来。它总是返回true。我不知道为什么,我推测它与我怎么写我经常EX pression做。任何帮助将是AP preciated。

 私有静态布尔的isValid(字符串str)
{
    布尔有效= FALSE;    正则表达式章=新的正则表达式((@A-ZA-Z +));    如果(reg.Match(STR).Success)
        有效= FALSE;
    其他
        有效=真实的;     返回有效的;
}


解决方案

正确的方法是,像这样:

 私有静态布尔的isValid(字符串str)
{
    返回Regex.IsMatch(STR,@^ [A-ZA-Z] + $);
}

这code具有以下优点:


  • 使用静态方法,而不是每次都创建一个新的实例:静态方法缓存正规前pression

  • 修正了正则表达式。现在匹配,由一个或多个字符A-Z或A-Z中的任意字符串。没有其他字符。

  • 更短,可读性。

I want to check if a string inputted in a character between a-z or A-Z. Somehow my regular expression doesn't seem to pick it up. It always returns true. I am not sure why, I gather it has to do with how I am writing my regular expression. Any help would be appreciated.

private static bool isValid(String str)
{
    bool valid = false;

    Regex reg = new Regex((@"a-zA-Z+"));

    if (reg.Match(str).Success)
        valid = false;
    else 
        valid  = true;     

     return valid;
}

解决方案

The right way would be like so:

private static bool isValid(String str)
{
    return Regex.IsMatch(str, @"^[a-zA-Z]+$");
}

This code has the following benefits:

  • Using the static method instead of creating a new instance every time: The static method caches the regular expression
  • Fixed the regex. It now matches any string that consists of one or more of the characters a-z or A-Z. No other characters are allowed.
  • Much shorter and readable.

这篇关于C#正则表达式:检查" A-Z"和" A-Z"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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