[英]Check multiple words in a string using Contains method
I want to check multiple words in a string and want to replace them. 我想检查字符串中的多个单词,并希望替换它们。 Suppose that my string is
假设我的字符串是
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
}
How can check multiple words not by using loops, and in one flow. 如何不使用循环和一次检查就可以检查多个单词。 I am new to c#.
我是C#的新手。 Please help me out
请帮帮我
You don't need the if, just do: 您不需要if,只需执行以下操作:
var newStr = str.Replace("(R)"," ").Replace("(work)"," ");
If you want a space as you say or: 如果您想说一个空格或:
var newStr = str.Replace("(R)",string.Empty).Replace("(work)",string.Empty);
If you want an empty string. 如果您想要一个空字符串。
You could use the Regex.Replace
method. 您可以使用
Regex.Replace
方法。
string str = "20148(R)/(work)24553(r)";
string str2 = Regex.Replace(str, "[(](?:R|work)[)]", "", RegexOptions.IgnoreCase);
Console.Writeline(str2); //prints 20148/24553
This says take the string str
and match the pattern [(R|work)]
and replace any instances with ""
ignoring the case of the input string when doing the comparison (so it matches (R)
and (r)
). 这表示采用字符串
str
并匹配模式[(R|work)]
并在进行比较时忽略输入字符串的大小写,并用""
替换任何实例(因此它匹配(R)
和(r)
)。
Put R
and r
inside a character class to match both letters. 将
R
和r
放在字符类中以匹配两个字母。
string str = "20148(R)/(work)24553(r)";
string result = Regex.Replace(str, @"\((?:[Rr]|work)\)", "");
Console.WriteLine(result);
OR 要么
string str = "20148(R)/(work)24553(r)";
string result = Regex.Replace(str, @"(?i)\((?:R|work)\)", "");
Console.WriteLine(result);
Pattern Explanation: 模式说明:
(?i)
( i modifier ) would turn on the case-insensitive mode. (?i)
( i修饰符 )将打开不区分大小写的模式。 So it would match both upper and lowercase letters. \\(
Matches a literal (
symbol. \\(
匹配文字(
符号。 (?:)
Non-capturing group. (?:)
非捕获组。 R|work
Matches a letter R
or string work
.(case-insensitive match) R|work
匹配字母R
或字符串work
。(不区分大小写的匹配) \\)
Matches a literal )
symbol. \\)
与文字)
符号匹配。 With regex you can replace this 使用正则表达式,您可以替换它
[(]\b(?:R|work)\b[)]
With empty string ""
空字符串
""
Edit: 编辑:
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.