我需要在我的字符串中找到模式,然后剪切出包含该模式的整个部分。我将举例说明我需要做的事情:
我有这样的字符串:
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
答案 0 :(得分:1)
您可以使用正则表达式或简单的字符串操作来解决它。
这是使用简单的字符串操作:
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