Prasanna Kumar J
Prasanna Kumar J

Reputation: 327

C# substring with multiple characters

Please find the below sample possible strings

How do we extract text only from the above string list (e.g., Orange+bhabha,Mango>foo,Apple Https://test.com,Grape etc..)?

Please find the below sample my tried Codesnip:

    eg:var str="Orange<<0";
    str.Split("<<")[0].Split("==")[0].Split(">>")[0];
    // Output : Orange

It is working fine. Is there an optimal solution to solve this issue?

Input -> Desired output 
"Orange+bhabha<<0" -> "Orange+bhabha"
"Mango>foo>>10" -> "Mango>foo"
"Apple Https://test.com<<5>>2" -> "Apple Https://test.com"
"Grape==50" -> "Grape"
"kiwi>>20<<5" -> "Kiwi"

Upvotes: 0

Views: 443

Answers (3)

JamesS
JamesS

Reputation: 2300

You could use a regular expression to replace all non-letters in the string with string.Empty

string result = Regex.Replace(<THE STRING>, @"[^A-Z]+", String.Empty);

However, the above will show all the letters in the string so if your string was something like 'kiwi<<02>>test' it would show 'kiwitest'.

After the latest revision, the following expression should work:

[^a-zA-Z:/.]+

Upvotes: 4

Darkk L
Darkk L

Reputation: 1045

Also you can try this

    foreach (var item in strList)
    {
        str = str.Replace(item, string.Empty);
    }

Upvotes: 0

Somar Zein
Somar Zein

Reputation: 170

You can use Split from string library:

string[] stringList = { "Orange+bhabha<<0", "Mango>foo>>10", "Apple Https://test.com<<5>>2", "Grape ==50", "kiwi>>20<<5" };
foreach (var str in stringList)
{
   var result = str.Split(new string [] { ">>", "<<", "==" },StringSplitOptions.None)[0];
   Console.WriteLine(result);
}

One of advantages is that you can modify the separator easily.

Upvotes: 2

Related Questions