简体   繁体   中英

Extracting Substring from string using regular expression

I have collection of batch numbers coming into the system(eg 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.

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.

How would I go about doing this please?

Just use a positive lookbehind:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM