c#中的多个字符串替换

时间:2012-07-31 08:49:41

标签: c# regex

我正在动态编辑正则表达式以匹配pdf中的文本,该文本可以在某些行的末尾包含连字符。

示例:

源字符串:

"consecuti?vely"

替换规则:

 .Replace("cuti?",@"cuti?(-\s+)?")
 .Replace("con",@"con(-\s+)?")
 .Replace("consecu",@"consecu(-\s+)?")

期望的输出:

"con(-\s+)?secu(-\s+)?ti?(-\s+)?vely"

替换规则是动态构建的,这只是导致问题的一个例子。

什么是执行这种多次替换的最佳解决方案,这将产生所需的输出?

到目前为止,我考虑过使用Regex.Replace并将该单词用可选项( - \ s + +)替换?在每个字符之间,但这不起作用,因为要替换的单词已在正则表达式上下文中包含特殊含义字符。

编辑:我的当前代码在替换规则重叠时不起作用,如上例所示

private string ModifyRegexToAcceptHyphensOfCurrentPage(string regex, int searchedPage)
    {
        var originalTextOfThePage = mPagesNotModified[searchedPage];
        var hyphenatedParts = Regex.Matches(originalTextOfThePage, @"\w+\-\s");
        for (int i = 0; i < hyphenatedParts.Count; i++)
        {
            var partBeforeHyphen = String.Concat(hyphenatedParts[i].Value.TakeWhile(c => c != '-'));

            regex = regex.Replace(partBeforeHyphen, partBeforeHyphen + @"(-\s+)?");
        }
        return regex;
    }

4 个答案:

答案 0 :(得分:2)

这个程序的输出是“con( - \ s +)?secu( - \ s +)?ti?( - \ s +)?vely”; 我理解你的问题,我的代码可以完全解决你的问题。

class Program
    {
        class somefields
        {
            public string first;
            public string secound;
            public string Add;
            public int index;
            public somefields(string F, string S)
            {
                first = F;
                secound = S;
            }

        }
    static void Main(string[] args)
    {
        //declaring output
        string input = "consecuti?vely";
        List<somefields> rules=new List<somefields>();
        //declaring rules
        rules.Add(new somefields("cuti?",@"cuti?(-\s+)?"));
        rules.Add(new somefields("con",@"con(-\s+)?"));
        rules.Add(new somefields("consecu",@"consecu(-\s+)?"));
        // finding the string which must be added to output string and index of that
        foreach (var rul in rules)
        {
            var index=input.IndexOf(rul.first);
            if (index != -1)
            {
                var add = rul.secound.Remove(0,rul.first.Count());
                rul.Add = add;
                rul.index = index+rul.first.Count();
            }

        }
        // sort rules by index
        for (int i = 0; i < rules.Count(); i++)
        {
            for (int j = i + 1; j < rules.Count(); j++)
            {
                if (rules[i].index > rules[j].index)
                {
                    somefields temp;
                    temp = rules[i];
                    rules[i] = rules[j];
                    rules[j] = temp;
                }
            }
        }

        string output = input.ToString();
        int k=0;
        foreach(var rul in rules)
        {
            if (rul.index != -1)
            {
                output = output.Insert(k + rul.index, rul.Add);
                k += rul.Add.Length;
            }
        }
        System.Console.WriteLine(output);
        System.Console.ReadLine();
    }
} 

答案 1 :(得分:0)

您应该编写自己的解析器,它可能更容易维护:)。

也许你可以添加&#34;特殊字符&#34;围绕模式,以保护他们像&#34; ##&#34;如果字符串不包含它。

答案 2 :(得分:-1)

试试这个:

var final = Regex.Replace(originalTextOfThePage, @"(\w+)(?:\-[\s\r\n]*)?", "$1");

答案 3 :(得分:-1)

我不得不放弃一个简单的解决方案并自己编辑正则表达式。作为副作用,新方法只通过字符串两次。

private string ModifyRegexToAcceptHyphensOfCurrentPage(string regex, int searchedPage)
    {
        var indexesToInsertPossibleHyphenation = GetPossibleHyphenPositions(regex, searchedPage);
        var hyphenationToken = @"(-\s+)?";
        return InsertStringTokenInAllPositions(regex, indexesToInsertPossibleHyphenation, hyphenationToken);
    }

    private static string InsertStringTokenInAllPositions(string sourceString, List<int> insertionIndexes, string insertionToken)
    {
        if (insertionIndexes == null || string.IsNullOrEmpty(insertionToken)) return sourceString;

        var sb = new StringBuilder(sourceString.Length + insertionIndexes.Count * insertionToken.Length);
        var linkedInsertionPositions = new LinkedList<int>(insertionIndexes.Distinct().OrderBy(x => x));
        for (int i = 0; i < sourceString.Length; i++)
        {
            if (!linkedInsertionPositions.Any())
            {
                sb.Append(sourceString.Substring(i));
                break;
            }
            if (i == linkedInsertionPositions.First.Value)
            {
                sb.Append(insertionToken);
            }
            if (i >= linkedInsertionPositions.First.Value)
            {
                linkedInsertionPositions.RemoveFirst();
            }
            sb.Append(sourceString[i]);
        }
        return sb.ToString();
    }

    private List<int> GetPossibleHyphenPositions(string regex, int searchedPage)
    {
        var originalTextOfThePage = mPagesNotModified[searchedPage];
        var hyphenatedParts = Regex.Matches(originalTextOfThePage, @"\w+\-\s");
        var indexesToInsertPossibleHyphenation = new List<int>();
        //....
        // Aho-Corasick to find all occurences of all 
        //strings in "hyphenatedParts" in the "regex" string
        // ....
        return indexesToInsertPossibleHyphenation;
    }