检查字符串中的数字是否在C#中包含有效年份 [英] Check if a number in a string contains a valid year in c#

查看:94
本文介绍了检查字符串中的数字是否在C#中包含有效年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下字符串,需要确保该字符串中的数字为有效年份.因此,在这种情况下,2014年.

I have a the following string and need to ensure that the number in the string is a valid year. So in this case 2014.

var notesField = "Payment for the month ending 30 Nov 2014";
char[] whitespace = new char[] { ' ', '\t' };
string[] text = notesField.Split(
                          whitespace,
                          StringSplitOptions.RemoveEmptyEntries
                          );

推荐答案

从不建议以这种方式查找或验证年份的方法,但是如果您确定句子中将恰好有一个四位数的单词,则可以使用正则表达式匹配,如下所示.

The approach to find or validate year in this way is never recommended but if you are sure that there will be exactly one four digits word in the sentence then you can use regex match like below.

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        Regex regex = new Regex(@"\d{4}");
        Match match = regex.Match("Payment for the month ending 30 Nov 2014");
        if (match.Success)
        {
            Console.WriteLine(match.Value);
        }
    }
}

工作小提琴是此处

这篇关于检查字符串中的数字是否在C#中包含有效年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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