简体   繁体   中英

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

I need to find pattern in my string and then cut out whole part that contains that pattern. I'll give an example what I need to do:

I have string like this:

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

In that string I want to check if this pattern exists:

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

And If it is in my string so I want to cut out whole code that contains my pattern and it is separated with spaces:

AB/12/34/56/BA1590/A

You can solve it using regular expressions or simply string operations.

This is using simple string operations:

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

Output:

AB/12/34/56/BA1590/A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM