1

我正在动态编辑一个正则表达式以匹配 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

4 回答 4

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();
    }
} 
于 2012-07-31T11:07:17.923 回答
0

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

如果字符串不包含它,也许您可​​以在模式周围添加“特殊字符”以像“##”一样保护它们。

于 2012-07-31T08:52:49.223 回答
-1

试试这个:

var final = Regex.Replace(originalTextOfThePage, @"(\w+)(?:\-[\s\r\n]*)?", "$1");
于 2012-07-31T10:21:57.843 回答
-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;
    }
于 2012-07-31T11:32:02.047 回答