0

我知道这似乎很复杂,但我的意思是例如我有一个字符串

This is a text string 

我想搜索一个字符串(例如:文本)。我想找到这个字符串的第一次出现,它出现在给定的另一个字符串(例如:is)之后,并且替换应该是另一个给定的字符串(例如:replace)

所以结果应该是:

This is a textreplace string

如果 text 是,This text is a text string那么结果应该是This text is a textreplace string

我需要一种方法(赞赏扩展方法):

public static string AppendFirstOccurranceAfter(this string originalText, string after, string oldValue, string newValue)
// "This is a text string".ReplaceFirstOccurranceAfter("is", "text", "replace")
4

2 回答 2

1

这是扩展方法:

        public static string CustomReplacement(this string str)
        {
            string find = "text"; // What you are searching for
            char afterFirstOccuranceOf = 'a'; // The character after the first occurence of which you need to find your search term.
            string replacement = "$1$2replace"; // What you will replace it with. $1 is everything before the first occurrence of 'a' and $2 is the term you searched for.

            string pattern = $"([^{afterFirstOccuranceOf}]*{afterFirstOccuranceOf}.*)({find})";

            return Regex.Replace(str, pattern, replacement);
        }

你可以像这样使用它:


string test1 = "This is a text string".CustomReplacement();
string test2 = "This text is a text string".CustomReplacement();

此解决方案使用 C# 正则表达式。Microsoft 的文档在这里:https ://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference

于 2020-04-16T15:23:35.770 回答
1

您必须找到要匹配的第一个单词的索引,然后使用该索引,从该索引开始再次搜索第二个单词,然后您可以插入新文本。您可以使用IndexOf 方法找到所述索引(检查它的重载)。

这是一个以(我希望)可读的方式编写的简单解决方案,并且您可以改进以使其更惯用:

    public static string AppendFirstOccurranceAfter(this string originalText, string after, string oldValue, string newValue) {
    var idxFirstWord = originalText.IndexOf(after);
    var idxSecondWord = originalText.IndexOf(oldValue, idxFirstWord);
    var sb = new StringBuilder();

    for (int i = 0; i < originalText.Length; i++) {
        if (i == (idxSecondWord + oldValue.Length))
            sb.Append(newValue);
        sb.Append(originalText[i]);
    }

    return sb.ToString();
}
于 2020-04-16T15:32:42.370 回答