开发者

How do I extract a string of text in c#

开发者 https://www.devze.com 2023-04-12 05:42 出处:网络
i am having trouble splitting a string in c# have a string (text in textbox0) start and dffdfdddddddfd<m>one</m><m>two</m><m>three</m><m>four</m>dbfjnb

i am having trouble splitting a string in c# have a string (text in textbox0)

start and dffdfdddddddfd<m>one</m><m>two</m><m>three</m><m>four</m>dbfjnbjvbnvbnjvbnv and end

and I want to extract the text between <m> and </m> when click in button1 and i need 3 output :

output 1 : one two three four开发者_StackOverflow (output to textbox1)

output 2 : four (output to textbox2)

output 3 : one (output to textbox3)

what do i do ?

how would I do this?

please give me full code for button1_Click

thanks and regards.


You can try a regular expression to capture the four values in a list, either using LINQ:

List<string> results = Regex.Matches(s, "<m>(.*?)</m>")
                            .Cast<Match>()
                            .Select(m => m.Groups[1].Value)
                            .ToList();

Or for C# 2.0:

List<string> results = new List<string>();
foreach (Match match in Regex.Matches(s, "<m>(.*?)</m>"))
{
     results.Add(match.Groups[1].Value);
}

You can then use string.Join, Enumerable.First (or results[0]) and Enumerable.Last (or results[results.Length - 1]) to get the outputs you need.

If this is XML you should use an XML parser instead.


With customary warning against using Regex for XML and HTML:

You can extract text between <m> and </m> like so:

     string input =
            "start and dffdfdddddddfd<m>one</m><m>two</m><m>three</m><m>four</m>dbfjnbjvbnvbnjvbnv and end";
     var matches = Regex.Matches(input, "<m>(.*?)</m>");
     foreach (Match match in matches)
     {
        Console.WriteLine(match.Groups[1]);
     }


using System;
using System.Linq;
using System.Xml.Linq;

class Program{
    static void Main(string[] args){
        string data = "start and dffdfdddddddfd<m>one</m><m>two</m><m>three</m><m>four</m>dbfjnbjvbnvbnjvbnv and end";
        string xmlString = "<root>" + data + "</root>";
        var doc = XDocument.Parse(xmlString);
        var ie = doc.Descendants("m");
        Console.Write("output1:");
        foreach(var el in ie){
            Console.Write(el.Value + " ");
        }
        Console.WriteLine("\noutput2:{0}",ie.Last().Value);
        Console.WriteLine("output3:{0}",ie.First().Value);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消