简体   繁体   中英

Regex: Parse specific string with one 18-digit number

C#/.NET 4.0

I need to parse a string containing a 18-digit number. I also need the substrings at the left and right side.
Example strings:

string a = "Frl Camp Gerbesklooster 871687120000000691 OPLDN 2010 H1";
string b = "some text with spaces 123456789012345678 more text";

How it should be parsed:

string aParsed[0] = "Frl Camp Gerbesklooster";
string aParsed[1] = "871687120000000691";
string aParsed[2] = "OPLDN 2010 H1";

string bParsed[0] = "some text with spaces";
string bParsed[1] = "123456789012345678";
string bParsed[2] = "more text";

There is always that 18-digit number in the middle of the string. I'm an absolute newbie to Regex so I don't actually have a try of my own.
What is the best way to do this? Should I use regular expressions?
Thanks.

You can use something like the regex: (.*)(\d{18})(.*) .

The key here is to use {18} to specify that there must be exactly 18 digits and to capture each part in a group.

var parts = Regex.Matches(s, @"(.*)(\d{18})(.*)")
    .Cast<Match>()
    .SelectMany(m => m.Groups.Cast<Group>().Skip(1).Select(g=>g.Value))
    .ToArray();

Daniël,

Although the question is answered the following may be a useful reference for learning Reg Expressions.

http://txt2re.com

Regards, Liam

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