简体   繁体   中英

is there a regex for parsing a string possible?

Consider the following string:

01500343014501044801

I want to parse this string and fill 6 variables with it, they are filled from a fixed length in the string.

Now instead of doing the obvious:

string s1 = s.Substring(0, 3);
//...
string s2 = s.Substring(7, 8);
//...

Im wondering if there's a regex possible for doing this? Or does the .NET framework have a something like sscanf in C?

Yes it is possible, you can specify length of blocks (\\d{5})(\\d{4})(\\d{7})(\\d{4}) will capture 4 groups consisting of 5,4,7 and 4 digits respectfully.
Although comments to your question are spot on, RegEx will be slower.

    var myNumber = "01500343014501044801";
    var m = Regex.Matches(myNumber, @"\d{3}");

A quotation from Jamie Zawinski:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

Using regular expressions is costly in terms of performance. I'd stick to substrings in your case as you're not using any of the pattern matching facilities that regular expressions offer.

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