regex 如何在c#中使用正则表达式获取带空格字符串

wwtsj6pe  于 2023-02-20  发布在  C#
关注(0)|答案(1)|浏览(205)

我想得到字符串数据从段落,在字符串将有一个空格。
样本数据

my id is REG #22334 E112233
my name is xyz
my city is xyz

预期操作= 22334 E112233
代码

var myString= "my id is REG #22334 E112233
my name is xyz
my city is xyz";
var regex = new Regex(@"[1-3]\d{4}([ ]E\d{6})?$");
var id= regex.Match(myString).Value;

O/p = "";
mwngjboj

mwngjboj1#

由于要在行的末尾匹配$,因此需要使用multiline选项:

var regex = new Regex(@"[1-3]\d{4}(?: E\d{6})?$", RegexOptions.Multiline);
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
        var myString= @"my id is REG #22334 E112233
        my name is xyz
        my city is xyz";
        var regex = new Regex(@"[1-3]\d{4}(?: E\d{6})?$", RegexOptions.Multiline);
        var id= regex.Match(myString).Value;

        Console.WriteLine(id);
   }
}

输出:

22334 E112233

相关问题