demo stack
demo stack

Reputation: 103

Taking a substring from a string

I have a string like

string str = "<abc> hello </abc> <abc> world </abc>"

Output in List/Array :
hello
world

Now, I want to extract only texts between <abc> and </abc>. There can be n number of abc tags. So I just want the between text.
How can I do that.

I tried using split, but it does not give the between text.

Upvotes: 1

Views: 67

Answers (2)

user3470088
user3470088

Reputation: 48

you could split by space then filter out the two expressions you don't want. then add the ones you do to a list.

List<String> list1 = new List<String>();
string str = "<abc> hello </abc> <abc> world </abc>";
string[] array = str.Split(' ');
foreach (string word in array)
{
    if (word != "<abc>" && word != "</abc>")
    {
        list1.Add(word);
    }
}

Upvotes: 0

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

You can use regular expressions (regex), for example:

string str = "<abc> hello </abc> <abc> world </abc>";
string pattern = "<abc>(.*?)</abc>";

var matches = Regex.Matches(str, pattern);

var result = matches.Cast<Match>().Select(m => m.Groups[1].Value.Trim()).ToArray();

Hope this helps.

Upvotes: 7

Related Questions