简体   繁体   中英

What is a good approach for splitting this string in C#?

I need to split a string in C# that is formatted as follows:

"(11)123456(14)abc123(18)gt567"

With the desired result being a string array such as:

  • "(11)123456"
  • "(14)abc123"
  • "(18)gt567"

I'm guessing that a Regular Expression might be involved but that is one of my weak areas.

var s = "(11)123456(14)abc123(18)gt567";

Regex r = new Regex(@"\(\d+\)\w+");

var matches = r.Matches(s);

string[] array = new string[matches.Count];
for(int i = 0; i < matches.Count; i++)
    array[i] = matches[i].Captures[0].Value;
 var result = "(11)123456(14)abc123(18)gt567"
            .Split(new string[]{"("}, StringSplitOptions.RemoveEmptyEntries)
            .Select(i => "(" + i).ToList();

Something like:

string theString = "(11)123456(14)abc123(18)gt567";

Regex reSplit = new Regex(@"\(\d+\)[^\(]+");
var matches = reSplit.Matches(theString);

That will give you a collection of Match objects that you can then examine.

To get an array of strings:

var splits = matches.Cast<Match>().Select(m => m.Value).ToArray();

You can use a regex along with its Split method to get the array of parts.

var s = "(11)123456(14)abc123(18)gt567";
var pattern = new Regex(@"(\([^\(]+)");
var components = pattern.Split(s)

The pattern matches an left parenthesis followed by any number of characters up until the next left parenthesis.

If you need to deal with whitespace such as new lines, you might need to tweak the pattern or the RegexOptions a little.

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