簡體   English   中英

如何在c#中提取一串文本

[英]How do I extract a string of text in c#

我在c#中拆分字符串時遇到問題有一個字符串(textbox0中的文本)

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

我想在按鈕1中單擊時提取<m></m>之間的文本,我需要3個輸出:

輸出1 :一二三四(輸出到textbox1)

輸出2 :四(輸出到textbox2)

輸出3 :一(輸出到textbox3)

我該怎么辦 ?

我該怎么做?

請給我button1_Click的完整代碼

謝謝並恭祝安康。

您可以嘗試使用正則表達式捕獲列表中的四個值,使用LINQ:

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

或者對於C#2.0:

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

然后,您可以使用string.JoinEnumerable.First (或results[0] )和Enumerable.Last (或results[results.Length - 1] )來獲取所需的輸出。

如果這是XML,則應使用XML解析器。

對於使用Regex for XML和HTML的慣例警告:

您可以在<m></m>之間提取文本,如下所示:

     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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM