[英]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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.