Reg ex以固定字符串开头,以可变编号结束

时间:2016-05-27 09:13:12

标签: c# regex

我需要匹配以固定字符串These masters were created using开头并以变量[space][name][space][char][number]

结尾的字符串
These masters were created using Kevin O014
These masters were created using Jhon A039
These masters were created using Geeth P034
These masters were created using Jemes M077
These masters were created using Anne H058
These masters were created using JANE S345

有什么想法吗?

我试过这个^(These masters were created using).\s.[a-zA-Z].\s.[a-zA-Z].[0-9]{3}.$。它对我来说是希腊人

3 个答案:

答案 0 :(得分:1)

我会用这个:

These masters were created using [a-zA-Z]+ [a-zA-Z]\d+

请参阅demo

  • [a-zA-Z]+匹配一个名字(假设,简单名称,没有-,没有强调的字符)
  • [a-zA-Z]\d+匹配任意数字后跟的字母。如果您需要3位数
  • ,您可以更改为[a-zA-Z]\d{3}
string input = @"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>These masters were created using Smith J054<br>";
Regex regex = new Regex(@"These masters were created using [a-zA-Z]+ ([a-zA-Z]\d+)");

foreach (Match match in regex.Matches(input))
{
    Console.Out.WriteLine("Found a match : " + match);
    if(match.Groups.Count >= 2)
        Console.Out.WriteLine("Extract " + match.Groups[1].Value);
}

输出:

  

找到匹配项:这些大师是使用Smith J054

创建的      

提取J054

答案 1 :(得分:1)

^这些大师是使用[[a-zA-z \ S] * [[A-Za-z0-9] * $

创建的

确保在线计算器上使用多线匹配。

答案 2 :(得分:0)

不仅要验证,还要在最后获取名称和代码,您可以使用

\bThese masters were created using (?<Name>[A-Za-z]+)\s+(?<Code>[A-Za-z][0-9]{3})\b

请参阅regex demo

其中(?<Name>[A-Za-z]+)匹配任何1个以上的ASCII字母,并将其捕获到名为&#34的组中;名称&#34;,\s+匹配一个或多个空格,(?<Code>[A-Za-z][0-9]{3})匹配和捕获进入Group&#34; Code&#34;一封字母后面跟着3位数字(使用+代替{3}来匹配1位或更多位数。)

请注意\b是单词边界,有助于将较大字符串中的字符串与整个单词匹配。

在C#中:

var pattern = @"\bThese masters were created using (?<Name>\p{L}+)\s+(?<Code>\p{L}\d{3})\b";

Sample C# demo

using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var s = "aaaaaa These masters were created using Kevin O014\nThese masters were created using Jhon A039\nThese masters were created using Geeth P034\nThese masters were created using Jemes M077\nThese masters were created using Anne H058\nThese masters were created using JANE S345 aaaaa";
        var matches = Regex.Matches(s, @"\bThese masters were created using (?<Name>[A-Za-z]+)\s+(?<Code>[A-Za-z][0-9]{3})\b")
                    .Cast<Match>()
                    .Select(m=> string.Format("{0}: {1}", m.Groups["Name"].Value, m.Groups["Code"].Value))
                    .ToList();
        Console.WriteLine(string.Join("\n", matches));
    }
}