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



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

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(从字符串(20(中获取代码(20(和代码(10
(之后的数字字符串

预期答案:13132324 + 12423352

这可以使用正则表达式来完成吗?

谢谢

这完全取决于 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 的值是字母数字。

最新更新