我需要从文本中删除旁边带有分隔符的单词。我已经删除了单词,但我不知道如何同时删除分隔符。有什么建议吗?
目前我有:
static void Main(string[] args)
{
Program p = new Program();
string text = "";
text = p.ReadText("Duomenys.txt", text);
string[] wordsToDelete = { "Hello", "Thanks", "kinda" };
char[] separators = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };
p.DeleteWordsFromText(text, wordsToDelete, separators);
}
public string ReadText(string file, string text)
{
text = File.ReadAllText(file);
return text;
}
public void DeleteWordsFromText(string text, string[] wordsToDelete, char[] separators)
{
Console.WriteLine(text);
for (int i = 0; i < wordsToDelete.Length; i++)
{
text = Regex.Replace(text, wordsToDelete[i], String.Empty);
}
Console.WriteLine("-------------------------------------------");
Console.WriteLine(text);
}
结果应该是:
how are you?
I am good.
我有:
, how are you?
, I am . good.
Duomenys.txt
Hello, how are you?
Thanks, I am kinda. good.
请您参考如下方法:
你可以像这样构建一个正则表达式
\b(?:Hello|Thanks|kinda)\b[ .,!?:;() ]*
其中 \b(?:Hello|Thanks|kinda)\b 将匹配任何要删除的单词作为整个单词和 [ .,!?:;() ]* 将在要删除的单词之后匹配所有分隔符 0 次或多次。
char[] separators = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };
string[] wordsToDelete = { "Hello", "Thanks", "kinda" };
string SepPattern = new String(separators).Replace(@"\", @"\\").Replace("^", @"\^").Replace("-", @"\-").Replace("]", @"\]");
var pattern = $@"\b(?:{string.Join("|", wordsToDelete.Select(Regex.Escape))})\b[{SepPattern}]*";
// => \b(?:Hello|Thanks|kinda)\b[ .,!?:;() ]*
Regex rx = new Regex(pattern, RegexOptions.Compiled);
// RegexOptions.IgnoreCase can be added to the above flags for case insensitive matching: RegexOptions.IgnoreCase | RegexOptions.Compiled
DeleteWordsFromText("Hello, how are you?", rx);
DeleteWordsFromText("Thanks, I am kinda. good.", rx);
这是 DeleteWordsFromText 方法:
public static void DeleteWordsFromText(string text, Regex p)
{
Console.WriteLine($"---- {text} ----");
Console.WriteLine(p.Replace(text, ""));
}
输出:
---- Hello, how are you? ----
how are you?
---- Thanks, I am kinda. good. ----
I am good.
注意事项:
string SepPattern = new String(分隔符).Replace(@"\", @"\\").Replace("^", @"\^").Replace("-", @"\-").Replace("]", @"\]");- 它是将在字符类中使用的分隔符模式,因为只有^,-,\,]字符需要在字符类中转义,只有这些字符被转义$@"\b(?:{string.Join("|", wordsToDelete.Select(Regex.Escape))})\b"- 这将从单词构建交替删除并且只会将它们作为整个单词进行匹配。
图案细节
\b- 单词边界(?:- 非捕获组的开始:Hello-Hello字词|- 或Thanks-谢谢word|- 或者kinda-kinda单词
)- 组结束\b- 单词边界[ .,!?:;() ]*- 字符类中任何 0+ 个字符。
参见 regex demo .
