c# - Split after some value


Keywords:c# 


Question: 

I have this input:

The Title #14 first 324.36 USD Second-GUY 261 USD Third33 101 USD

and I want to split that string to save in db.

So The title #14 is a title and it might be 1 word or many but all of them has # and some int value (it might be #2222 as well)

and after that title I want to get first and 324.36, Second-GUY and 261 etc. How can I do that?

I know about split and so I can input.Split('#') but I don't know what to do with that int.

on the second side I'll split with USD

first value I want to be: The Title #14

second: first 324.36

third: Second-GUY 261

as it is in image:

enter image description here


2 Answers: 

This could help with the solution

string lsInput = "The Title #14 first 324.36 USD Second-GUY 261 USD Third33 101 USD";
var loMatch = Regex.Match(lsInput, @"(?<title>.*#\d+)\s(?<parts>.*)");
string lsTitle = loMatch.Groups["title"].Value; //The Title #14
var loParts = loMatch.Groups["parts"].Value.Split(new string[] { "USD" },  StringSplitOptions.RemoveEmptyEntries).
   Select(item => item.Trim()).ToList();

Output loParts:

Count = 3
[0]: "first 324.36"
[1]: "Second-GUY 261"
[2]: "Third33 101"
 

Regex Class is very suitable for a task like that, write a pattern and let Regex class to do the job.
here is an example that shows how to use Regex based on your string.
please read my comments inside the example:

private void button1_Click(object sender, EventArgs e)
{
    string Target = "The Title #14 first 324.36 USD Second-GUY 261 USD Third33 101 USD";
    var value = string.Empty;
    var pattern = "(The Title) ([#]{1})([0-9]{1,500})";

    if (Example(Target,pattern, ref value) == true) 
    {
        MessageBox.Show(value); // output: The Title #14
    }

    pattern = "(first) ([0-9]{1,500}(.)[0-9]{1,500})";

    if (Example(Target, pattern, ref value) == true) 
    {
        MessageBox.Show(value); // output: first 324.36, if you want only the number one way is to replace  MessageBox.Show(value); to MessageBox.Show(value.Replace("first",""));
    }

    pattern = "(Second-GUY) ([0-9]{1,500}(.)[0-9]{1,500})";

    if (Example(Target, pattern, ref value) == true) 
    {
        MessageBox.Show(value); // output: Second-GUY 261, if you want only the number one way is to replace  MessageBox.Show(value); to MessageBox.Show(value.Replace("Second-GUY",""));
    }
}

private bool Example(string Target,string pattern, ref string value)
{

    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern);
    bool ismatched = reg.IsMatch(Target);

    if (ismatched)
    {
        System.Text.RegularExpressions.Match match = reg.Match(Target);
        value = match.Value;
    }

    return ismatched;
}