首页 > 解决方案 > 用于从字符串中提取特定编号模式的 C# 正则表达式

问题描述

当使用

Regex fakturaMultiPattern = new Regex(@"(\d{4}-\d+)+");

但我无法提取这样的模式:“F2020-53/54 John Doe”,我想在其中提取“2020-53/54”。我试过:

Regex MultiSlashPattern = new Regex(@"^\d{4}-\d+/\d+");

我想,我很接近,但请帮忙!

标签: c#regexstringsearch

解决方案


这应该符合您的期望:

using System;
using System.Text.RegularExpressions;

namespace Reginator
{
    class Program
    {
        static void Main(string[] args)
        {
            var testString = @"F2020-53/54, 2020-54, 2020-56 John Doe";
            var matches = GetMatchedCollections(testString, @"([,]?[0-9]+\-[0-9]+\/[0-9]+|[,]?[0-9]+-[0-9]+)");

            Console.WriteLine(matches[0].ToString());
            Console.WriteLine(matches[1].ToString());
            Console.WriteLine(matches[2].ToString());

            // Output:
            //      2020-53/54
            //      2020 - 54
            //      2020 - 56
        }

        public static MatchCollection GetMatchedCollections(string stringToSearch, string pattern)
        {
            var regex = new Regex(pattern, RegexOptions.IgnoreCase);
            return regex.Matches(stringToSearch);
        }
    }
}

推荐阅读