使用正则表达式从字符串中提取子字符串

时间:2021-08-11 13:28:54

I have collection of batch numbers coming into the system(e.g 24132352454235000534) that are each 20 characters long. I would like to, using regular expression, extract, say the substring from 7 to 15, from each of my batch numbers.

我有进入系统的批号的集合(例如24132352454235000534),每个长度为20个字符。我想,使用正则表达式,从我的每个批号中提取,比如说从7到15的子字符串。

The reason I would like to use regular expressions is that the requirement is not to modify the existing code which is used by over 20 processes, but simply add the expression to the configuration so that it can be applied when needed by the right process.

我想使用正则表达式的原因是,要求不是修改20多个进程使用的现有代码,而只是将表达式添加到配置中,以便在正确的进程需要时应用它。

How would I go about doing this please?

我该怎么做呢?

2 个解决方案

#1


3  

Just use a positive lookbehind:

只需使用积极的lookbehind:

(?<=\d{6})\d{8}

See it here in action: http://regex101.com/r/eX5rZ9

请在此处查看:http://regex101.com/r/eX5rZ9

#2


0  

Try this regular expression:

试试这个正则表达式:

(\d{6})(\d{9})(\d{5})

Sample code:

示例代码:

string strRegex = @"(\d{6})(\d{9})(\d{5})";
RegexOptions myRegexOptions = RegexOptions.Multiline | RegexOptions.Singleline;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"24132352454235000534";
string strReplace = @"$2";  // corresponds to the 2nd group: (\d{9})

return myRegex.Replace(strTargetString, strReplace);

Final string:

最终字符串:

524542350

#1


3  

Just use a positive lookbehind:

只需使用积极的lookbehind:

(?<=\d{6})\d{8}

See it here in action: http://regex101.com/r/eX5rZ9

请在此处查看:http://regex101.com/r/eX5rZ9

#2


0  

Try this regular expression:

试试这个正则表达式:

(\d{6})(\d{9})(\d{5})

Sample code:

示例代码:

string strRegex = @"(\d{6})(\d{9})(\d{5})";
RegexOptions myRegexOptions = RegexOptions.Multiline | RegexOptions.Singleline;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"24132352454235000534";
string strReplace = @"$2";  // corresponds to the 2nd group: (\d{9})

return myRegex.Replace(strTargetString, strReplace);

Final string:

最终字符串:

524542350