替换全部或部分字符串

时间:2018-12-31 08:47:31

标签: c# replace

在C#中,我将在与整个字符串或字符串的一部分匹配的字符串中使用“替换”:

我的模式example string

我的琴弦

This is the first example string
This is the second example

我想要得到的东西

This is the first
This is the second

如果我使用.Replace(pattern, string),我只会获得第一个结果,而不是第二个。

请有人可以帮助我吗?

下面是一个更详尽的示例:

Golf 7ª serie
GOLF 1.6 TDI TREND

Golf 7ª serie
Golf 1.6 TDI 90 CV 5p. Business Trendline BlueMotion Tech.

Freelander 2ª serie
Freelander 2.2 TD4 S.W. XS

Juke
Juke 1.5 dCi Start&Stop Acenta

如您所见,在前三个示例中,字符串中的模式部分匹配,而在第四个示例中,字符串中的模式完全匹配。 我想获得:

1.6 TDI TREND
1.6 TDI 90 CV 5p. Business Trendline BlueMotion Tech.
2.2 TD4 S.W. XS
1.5 dCi Start&Stop Acenta

因此,第一个字符串中包含的所有单词都必须从第二个字符串中删除

5 个答案:

答案 0 :(得分:0)

使用以下命令应从起始字符串中删除“ example”和“ string”。

using System.Text.RegularExpressions;

var result = Regex.Replace("This is the first example string", "(example|string)?", "" );

答案 1 :(得分:0)

尝试一下。这是一个通用的解决方案。

static void Main(string[] args)
{
    var fs = "This is the first example string";
    var ss = "This is the second example";
    var patternString = "example string";

    var patterns = patternString.Split(" ");

    foreach (string pattern in patterns)
    {
        fs = fs.Replace(pattern, "");
        ss = ss.Replace(pattern, "");
    }

}

答案 2 :(得分:0)

您可以遍历模式中的每个单词,并将它们逐个替换

var val = "This is the first example string";
var pattern = "example string";

foreach(var removeWord in pattern.Split(null))
{
    val = val.Replace(removeWord, string.Empty);
}

答案 3 :(得分:0)

如果您想在示例之前完成所有操作,最简单的方法是:

string substring = yourstring.Substring(0, one.IndexOf("example"));

正则表达式示例也可用:

Match result = Regex.Match("yourstring", @"^.*?(?=example)");
Console.WriteLine(result);

答案 4 :(得分:0)

一种有效的方法是尽可能避免使用Trigger

在处理涉及包含个问题的任务时,使用集合通常是最佳选择:

string.Replace