簡體   English   中英

如何在字符串中查找模式並切出包含該模式的部分-C#

[英]How to find pattern in string and cut out part that contains that pattern - C#

我需要在字符串中找到模式,然后切出包含該模式的整個部分。 我將舉一個例子,我需要做什么:

我有這樣的字符串:

string text = "Some random words here EK/34 54/56/75 AB/12/34/56/BA1590/A and more random stuff...";

在該字符串中,我想檢查此模式是否存在:

string whatImLookinFor = "12/34/56/";

並且如果它在我的字符串中,那么我想剪切出包含我的模式的整個代碼,並用空格分隔:

AB/12/34/56/BA1590/A

您可以使用正則表達式或簡單的字符串操作來解決它。

這是使用簡單的字符串操作:

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var text = "Some random words here EK/34 54/56/75 AB/12/34/56/BA1590/A and more random stuff...";
        var whatImLookinFor = "12/34/56/";

        // check if text contains it _at all_
        if (text.Contains(whatImLookinFor))
        {           
            // split the whole text at spaces as specified and retain those parts that 
            // contain your text
            var split = text.Split(' ').Where(t => t.Contains(whatImLookinFor)).ToList();

            // print all results to console
            foreach (var s in split)
                Console.WriteLine(s);
        }
        else
            Console.WriteLine("Not found");

        Console.ReadLine();
    }
}

輸出:

AB/12/34/56/BA1590/A

暫無
暫無

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

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