首页 > 解决方案 > 如何防止撇号仅从字符串中间被剥离?

问题描述

我需要保留仅包含字母数字字符、连字符和撇号的单词。目前除了撇号外,我什么都有。使用以下代码删除了诸如 hadn't、dids 和 ain't 之类的撇号:

Regex onlyAlphanumericAndDash = new Regex("[^a-zA-Z0-9 -]");
. . .
foreach (string line in doc1StrArray) // doc1StrArray populated in FindAndStorePhrasesFoundInBothDocs()
{
    trimmedLine = line;
    // first replace the "long dash" with a space (otherwise the dashed words run together:
    // "consecrated—we" becomes "consecratedwe"
    trimmedLine = trimmedLine.Replace("—", " ");
    trimmedLine = onlyAlphanumericAndDash.Replace(trimmedLine, "");
    string[] subLines = trimmedLine.Split();
    foreach (string whirred in subLines)
    {
        if (String.IsNullOrEmpty(whirred)) continue;
        _whirred = whirred.Trim();
        iWordsInDoc1++;
        slAllDoc1Words.Add(_whirred);
        if (IgnoreWord(_whirred)) continue;
        InsertIntoWordStatsTable(_whirred, 1, 0);
    }
}

我需要保留撇号,但前提是它们在一个单词内。换一种说法,单词末尾的撇号应该被剪掉,开头的撇号也应该剪掉(当它是单引号时);但是单词中的撇号- 换句话说,那些表示收缩的,例如“没有” - 应该被保留。

我需要添加什么到正则表达式或者我需要如何修改它来完成这个?

标签: c#regexapostrophe

解决方案


我对您subLines创建的变量名称(暗示文本行)有点困惑Split()- 无参数拆分将在空格上拆分。因此 subLines 是否包含单词或行?我认为,尽管有名称,但它包含单词,因此您可以将正则表达式修改为:

[^a-zA-Z0-9 '-]

这将留下所有撇号。注意:我把它放在之前-而不是之后,所以它没有定义范围(如A-Zis)的风险from (space) to (apostrophe)- 如果您已经尝试过,请记住这一点;-在字符类中使用并且您想-成为字符而不是表示“范围”时,将其作为^类中的第一件事(在 not 之后)或最后一件事

您可以使用 - 删除单词末尾的撇号whirred.Trim('\'')- 没有任何必要调用whirred.Trim()删除空格,因为字符串已经在空格上拆分,因此其中不会留下任何空格。两者Trim()并在该方法Split()定义为 whitedpace 的任何字符上拆分Char.IsWhitespace(c)


推荐阅读