[英]How to match words with combination of letters and numbers but avoid words with only numbers
[英]How to replace text in a sentence but avoid certain words/letters?
所以我有一個人的全名:
string fullName = "Bill Richardson";
假設我有這句話:
string sentence = "Richardson had a bike and he loved it";
但是該句子僅包含該人的姓氏,因此我將其替換為:
string modifiedSentence = null;
string[] senSplit = sentence.Split(' ');
foreach(string word in senSplit)
{
if(fullName.Contains(word))
{
modifiedSentence = sentence.Replace(word,fullName);
}
}
現在,我希望ModifySentence為:
比爾·理查森(Bill Richardson)有一輛自行車,他很喜歡
但是很顯然(我發現了問題),如果fullName甚至包含單詞“ a”,它就會被全名替換,從而以如下形式結束:
比爾·理查森(Bill Richardson)擁有比爾·理查森(Bill Richardson)自行車,他很喜歡
那是一場災難,不是嗎? :)如果可能的話,我該怎么做? 謝謝
你可以這樣做
modifiedSentence = new Regex(string.Join("|", fullName
.Split(' '))).Replace(sentence, fullName, 1);
Console.WriteLine(modifiedSentence);
如果您不知道姓氏是全名中的第一名還是第二名,則必須在兩個名上都進行迭代,而不是檢查它是否包含單詞,請測試兩個單詞之間的等效性。 請注意,如果fullName已包含在原始句子中,則此操作將無效。
var nameParts=fullName.Split(' ');
string modifiedSentence = null;
string[] senSplit = sentence.Split(' ');
foreach(string part in nameParts)
{
foreach(string word in senSplit)
{
if(nameParts.Equals(word))
{
modifiedSentence = sentence.Replace(word,fullName);
}
}
}
盡管可以以更緊湊的內聯方式完成此操作,但我認為這將更易於理解,並且更類似於您的原始代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.