c# - 如何防止撇号仅从字符串中间被剥离?
问题描述
我需要保留仅包含字母数字字符、连字符和撇号的单词。目前除了撇号外,我什么都有。使用以下代码删除了诸如 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);
}
}
我需要保留撇号,但前提是它们在一个单词内。换一种说法,单词末尾的撇号应该被剪掉,开头的撇号也应该剪掉(当它是单引号时);但是单词中的撇号- 换句话说,那些表示收缩的,例如“没有” - 应该被保留。
我需要添加什么到正则表达式或者我需要如何修改它来完成这个?
解决方案
我对您subLines
创建的变量名称(暗示文本行)有点困惑Split()
- 无参数拆分将在空格上拆分。因此 subLines 是否包含单词或行?我认为,尽管有名称,但它包含单词,因此您可以将正则表达式修改为:
[^a-zA-Z0-9 '-]
这将留下所有撇号。注意:我把它放在之前-
而不是之后,所以它没有定义范围(如A-Z
is)的风险from (space) to (apostrophe)
- 如果您已经尝试过,请记住这一点;-
在字符类中使用并且您想-
成为字符而不是表示“范围”时,将其作为^
类中的第一件事(在 not 之后)或最后一件事
您可以使用 - 删除单词末尾的撇号whirred.Trim('\'')
- 没有任何必要调用whirred.Trim()
删除空格,因为字符串已经在空格上拆分,因此其中不会留下任何空格。两者Trim()
并在该方法Split()
定义为 whitedpace 的任何字符上拆分Char.IsWhitespace(c)
推荐阅读
- azure - SFTP 连接自定义/参数化
- android - 如何在手机上访问 HttpServer?
- php - json php用ajax什么都不返回
- amazon-s3 - AWS PHP SDK S3:PutObject() 访问被拒绝,即使 SDK 用户账户具有完全权限
- ipywidgets - 如何调整 matplotlib 图形的大小以自动匹配 ipywidgets.Output() 大小?
- objective-c - 如何在目标 C 中使用 SHA512 创建 RSA 密钥对
- php - 试图在 Laravel 中组织 toJson 数据
- html - 支持IE!解决 IE 中的嵌套媒体查询?
- excel - COUNTIF 公式显示 0 直到单击单元格,然后再次单击
- ios - Couchbase 执行查询很慢