繁体   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