regex 如何获得一个文本,这是开始与1-3,并有4位数后,然后空格和E和6位数在.net使用正则表达式

jgwigjjp  于 2023-02-17  发布在  .NET
关注(0)|答案(1)|浏览(69)

正则表达式[1 - 3][0 - 9] {4}(?:E [0 - 9] {6})?$

sample data
    successful my registration id is #12345 E112233 (should match)
    Successful my data is #22331 E001122          (should match)
    failing    12345                             (should not match)

预期OP

12345 E112233

22331 E001122

代码-

var content ="successful my registration id is #12345 E112233
Successful my data is #22331 E001122          
failing    12345";

       var regex = new Regex(@"[1-3]\d{4}([ ]E\d{6})?$",RegexOptions.Multiline);
       var REG_ID = regex.Match(myStringData).Value;
a14dhokn

a14dhokn1#

您可以使用

var REG_ID = Regex.Match(myStringData, @"#([1-3]\d{4}(?: E\d{6})?)$")?.Groups[1].Value;
// OR - if you use a lookbehind
var REG_ID = Regex.Match(myStringData, @"(?<=#)[1-3]\d{4}(?: E\d{6})?$")?.Value;

请参见regex demo

    • 图案详细信息**
  • #-首先查找#(?<=#)查找前面紧跟#字符的位置)
  • ([1-3]\d{4}(?: E\d{6})?)-然后捕获(至第1组):
  • [1-3]\d{4}-一个1/2/3数字+四个数字
  • (?: E\d{6})?-空格+E+六位数字的可选序列
  • $-字符串结束。

相关问题