【问题标题】:Using Regex to insert sequence numbering使用正则表达式插入序列号
【发布时间】:2017-08-28 21:25:27
【问题描述】:

目前(使用 C#)我使用字符串方法 InstrSubstringInsert 将节号放入字符串中。尽管该方法工作正常,但它非常混乱且不太易于管理,因为我需要扩展它,因为后台还有其他事情发生。 我想知道是否可以使用 Regex 插入节号而不是使用标准字符串方法?如果是这样,它是如何完成的?

例如:

原始字符串

敏捷的红狐狸。跳过懒狗?敏捷的红狐狸! “跳过”懒狗。

使用正则表达式时的输出

1) 敏捷的红狐。 2)跳过懒狗? 3) 快红 狐狸! “4)跳过”懒狗。

PS:这是我在没有 Regex 的情况下使用的当前方法:

public string[] ApplyContentNumbering(string[] lines)
{
    int count = 1;
    if (lines != null && lines.Length > 0)
    {
        lines[0] = String.Format("{0} {1}", Chapter, lines[0].Substring(0));
        bool isOpen = false;

        for (int index = 1; index < lines.Length; index++)
        {
            count++;
            lines[index] = String.Format("{0} {1}", count, lines[index].Substring(0));

            if (lines[index].IndexOf("\"") > 0)
            {
                for (int c = 0; c < lines[index].Length; c++)
                {
                    if (lines[index].Substring(c, 1).Equals("\""))
                    {
                        if (isOpen == false)
                        {
                            count++;
                            lines[index] = lines[index].Insert(c + 1, String.Format("{0}", count));
                            isOpen = true;
                        }
                        else
                        {
                            isOpen = false;
                        }
                    }
                }
            }
        }
    }
}

【问题讨论】:

  • 有什么要求?什么时候插入数字?
  • 您好 Wiktor,我想在每个句子的开头和每个语音标记的开头添加编号,因此序列号不断增加。
  • 我不确定正则表达式是否是正确的方法。我相信代码可以从一些重构中受益,因为我无法一眼看出它是如何工作的。将一些功能分离为独立于该特定方法的方法。例如将一行分成句子的方法。然后是另一个插入序列的方法,等等。
  • 看看here - N) 在正确的地方吗?
  • Yep N) 看起来正确,突出显示的文本段也正确。我不确定编号将如何增加?我是否需要对所有匹配项进行 foreach 并手动增加编号?我认为这可能是最好的选择?

标签: c# regex


【解决方案1】:

您可以在此处使用 近似(或“足够好”)方法,包括在字符串开头/标点符号之后添加递增数字,并在 1+ 个空格后跟一个大写字母.

这是C# demo

var pat = @"(^|\p{P}\s+)(""?\p{Lu})";
var s = "The quick red fox. Jumped over the lazy dog? The quick red fox! \"Jumped over\" the lazy dog.";
var cnt = 0;
var res = Regex.Replace(s, pat, m =>
        string.Format("{0}{1}) {2}", m.Groups[1].Value, ++cnt, m.Groups[2].Value));
Console.WriteLine(res);
// => 1) The quick red fox. 2) Jumped over the lazy dog? 3) The quick red fox! 4) "Jumped over" the lazy dog.

正则表达式 - (^|\p{P}\s+)("?\p{Lu}) - 匹配:

  • (^|\p{P}\s+) - 第 1 组捕获字符串或标点符号的开头和 1+ 个空格
  • ("?\p{Lu}) - 第 2 组捕获可选的 ",然后是大写字母。

要以更可靠的方式实际将文本拆分为句子,您最好使用一些 NLP 包。

【讨论】:

  • 啊,你正在使用 linq 来进行替换,太棒了!我从没想过你能做到这一点。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
相关资源
最近更新 更多