簡體   English   中英

使用Contains方法檢查字符串中的多個單詞

[英]Check multiple words in a string using Contains method

我想檢查字符串中的多個單詞,並希望替換它們。 假設我的字符串是

str= 20148(R)/(work)24553(r)
if(str.contains(("R)" || str.Contains("(work)"))
{
   //Here I have to replace (R) and (Work) with space "". 
   // so that my string should be like this 20148/24553
}

如何不使用循環和一次檢查就可以檢查多個單詞。 我是C#的新手。 請幫幫我

您不需要if,只需執行以下操作:

var newStr = str.Replace("(R)"," ").Replace("(work)"," ");

如果您想說一個空格或:

var newStr = str.Replace("(R)",string.Empty).Replace("(work)",string.Empty);

如果您想要一個空字符串。

您可以使用Regex.Replace方法。

string str = "20148(R)/(work)24553(r)";
string str2 = Regex.Replace(str, "[(](?:R|work)[)]", "", RegexOptions.IgnoreCase);
Console.Writeline(str2); //prints 20148/24553

這表示采用字符串str並匹配模式[(R|work)]並在進行比較時忽略輸入字符串的大小寫,並用""替換任何實例(因此它匹配(R)(r) )。

Rr放在字符類中以匹配兩個字母。

string str = "20148(R)/(work)24553(r)";
string result = Regex.Replace(str, @"\((?:[Rr]|work)\)", "");
Console.WriteLine(result);

愛迪生

要么

string str = "20148(R)/(work)24553(r)";
string result = Regex.Replace(str, @"(?i)\((?:R|work)\)", "");
Console.WriteLine(result);

愛迪生

模式說明:

  • (?i)i修飾符 )將打開不區分大小寫的模式。 因此,它將匹配大寫和小寫字母。
  • \\(匹配文字(符號。
  • (?:)非捕獲組。
  • R|work匹配字母R或字符串work 。(不區分大小寫的匹配)
  • \\)與文字)符號匹配。

使用正則表達式,您可以替換它

[(]\b(?:R|work)\b[)]

空字符串""

編輯:

 string str1 = "20148(R)/(work)24553(r)"; 
  string str2 = Regex.Replace(str1, "[(]\b(?:R|work)\b[)]", "", RegexOptions.IgnoreCase);
  Console.Writeline(str2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM