简体   繁体   中英

Dividing a string using regular expression in C#

I have a string like this :

"John William Doe 250 / 1000 Adam Smith 500 / 1000 Jane Black 250 / 1000"

As you can see, the string consists of people's names and their shares. There can be any number of people (and shares) and people's names can consist of any number of words.

How can I divide this string to three strings like this :

"John William Doe 250 / 1000"
"Adam Smith 500 / 1000"
"Jane Black 250 / 1000"

I know I need to use regular expression but I couldn't do it myself. Any help is appreciated. Thanks.

([a-zA-Z ]*)*[0-9]* \\/ [0-9]*

You start with looking for name with a space, and repeating those.

You continue with the number, the slash and the other number

Note the spaces.

I know this is not that difficult problem and there's already some answer in comments, I still want to paste code for the OP:

    static void Main(string[] args)
    {
        string all = @"John William Doe 250 / 1000 Adam Smith 500 / 1000 Jane Black 250 / 1000";
        Regex r = new Regex(@"(?:\w+\s+)+\d+\s+/\s+\d+");
        foreach (Match m in r.Matches(all))
        {
            Console.WriteLine(m.Groups[0]);
        }
        Console.ReadLine();
    }

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