Checking if a string contains a specific word C#
14,305
Solution 1
Try specifying word boundaries (\b
):
if(Regex.IsMatch(str, @"\bhi\b"))
Solution 2
private static bool CheckIfExists(string sourceText, string textToCheck)
{
return sourceText.Split(' ').Contains(textToCheck);
}
Author by
user3121357
Updated on June 16, 2022Comments
-
user3121357 almost 2 years
I am checking these strings to see if they contain the word "hi" and returning true if they do. otherwise i am returning false. the string "high up should return false but is returning true. How can i fix this?
public static bool StartHi(string str) { if (Regex.IsMatch(str, "hi")) { return true; } else return false; } static void Main(string[] args) { StartHi("hi there"); // -> true StartHi("hi"); // -> true StartHi("high up"); // -> false (returns true when i run) }
-
DanKodi almost 10 yearsSo, Isn't a word a substring?