使用正则表达式验证C#中的输入格式 [英] using regex to validate input formatting in C#

查看:88
本文介绍了使用正则表达式验证C#中的输入格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题(我今天脑筋急转弯):

This is a super basic question (I am brain dead today):

如何使用正则表达式在输入中进行验证,以查看: 1)如果输入采用某种形式 2)如果输入全部为大写字母(将输入强制转换为大写字母是不可行的)

How do I validate in input using regexes, to see: 1) if the input is in a certain form 2) if the input is all caps (just casting the input to caps is not feasible for this)

我想确保我的输入格式为XX_XX.这是我所拥有的:

I want ot make sure my inputs are in the form XX_XX. Here isi what I have:

public bool IsKosher(string input)
{
    Regex r = new Regex(input);
    if(r.Matches([A-Z]_[A-Z]))
    {
        return true;
    }
    return false;     
}

有什么想法为什么不编译?

Any ideas why it's not compiling?

谢谢!

推荐答案

您缺少双引号,将参数放在错误的位置,并且不需要if语句:

You are missing double quotes, you put parameters in wrong places, and you do not need an if statement:

public bool IsKosher(string input) {
    return Regex.IsMatch(input, "[A-Z]{2}_[A-Z]{2}");
}

这篇关于使用正则表达式验证C#中的输入格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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