使用正则表达式从复杂的字符串中获取数据

时间:2018-09-20 07:41:54

标签: c# regex string

我需要从复杂的字符串中获取所需的数据,如下所示:

1)(99)00614141414167890(20)13132324(10)12423352(50)465654(30)96(37)6

2)(20)13132324(10)12423352(50)465654(30)96(37)6

要求:
1)从(字符串1)中获取代码(99)之后的数字
   预期的答案将是:00614141414167890

2)从字符串(2)中获取Code(20)和code(10)之后的数字字符串。

预期答案:13132324 + 12423352

可以使用正则表达式吗?

谢谢

1 个答案:

答案 0 :(得分:0)

这取决于AI之后的字符串是固定大小还是可变长度,以及AI和之后的值是否可选。

下面是(20)13132324(10)12423352(50)465654(30)96(37)6的示例。您应该能够根据自己的目的进行调整。注意,我还没有测试过。

string pattern = @"(20)([0-9]{8})(10)([a-zA-Z0-9]{8})(50)([0-9]{6})(30)([0-9]{2})(37)([0-9]{1})";
var match = Regex.Match( yourBarcode, pattern );
if ( match != null && match.Groups.Count == 11 )
{
    // examples: 
    // barcode: "(20)13132324(10)12423352(50)465654(30)96(37)6" 
    // 20firstCode10secondCode50thrirdCode30fourthCode37lastDigit
    // match.Groups[ 0 ].Value - whole barcode
    // "20131323241012423352504656543096376"
    // match.Groups[ 1 ].Value - AI(20)
    // "20"
    // match.Groups[ 2 ].Value - firstCode
    // "13132324"
    // match.Groups[ 3 ].Value - AI(10)
    // "10"
    // match.Groups[ 4 ].Value - secondCode
    // "12423352"
    // match.Groups[ 5 ].Value - AI(50)
    // "50"
    // match.Groups[ 6 ].Value - thirdCode
    // "465654"
    // match.Groups[ 7 ].Value - AI(30)
    // "30"
    // match.Groups[ 8 ].Value - fourthCode
    // "96"
    // match.Groups[ 9 ].Value - AI(37)
    // "37"
    // match.Groups[ 10 ].Value - lastDigit
    // "6"
    string code20 = match.Groups[ 2 ].Value;
    string code10 = match.Groups[ 4 ].Value;
}

在该示例中,我假设AI的大小均为固定值,是必填项,并且AI的值= 20、50、30、37是数字,而AI = 10的值是字母数字。