0

Please find the below sample possible strings

  • Orange+bhabha<<0
  • Mango>foo>>10
  • Apple Https://test.com<<5>>2
  • Grape==50
  • kiwi>>20<<5

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"
2
  • Why don't you use regex to extract it? Commented Apr 1, 2022 at 12:46
  • What is "Codesnip"? code snippet? Or the name of a web site? Commented Apr 6, 2022 at 10:50

3 Answers 3

4

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:/.]+
Sign up to request clarification or add additional context in comments.

6 Comments

Minor tweak: [^a-zA-Z] to allow lower case.
@Joe Yep. You're right
Sorry I have edited this post, Kindly please recheck
But this solution ignoring all characters eg Mango-foo changed to Mangofoo
@PrasannaKumarJ That's because I answered the original question How do we extract text only from above string list
|
2

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.

Comments

0

Also you can try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.