Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

379
Views
Get only Whole Words from a .Contains() statement

I've used .Contains() to find if a sentence contains a specific word however I found something weird:

I wanted to find if the word "hi" was present in a sentence which are as follows:

The child wanted to play in the mud

Hi there

Hector had a hip problem

if(sentence.contains("hi"))
{
   //
}

I only want the SECOND sentence to be filtered however all 3 gets filtered since CHILD has a 'hi' in it and hip has a 'hi' in it. How do I use the .Contains() such that only whole words get picked out?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Try using Regex:

if (Regex.Match(sentence, @"\bhi\b", RegexOptions.IgnoreCase).Success)
{
    //
};

This works just fine for me on your input text.

over 4 years ago · Santiago Trujillo Report

0

Here is a Regex solution:

Regex has a word boundary anchor using \b

Also, if the search string can come from user input, you might consider escaping the string using Regex.Escape

This example should filter a list of strings the way you want.

 string findme = "hi"; string pattern = @"\b" + Regex.Escape(findme) + @"\b"; Regex re = new Regex(pattern,RegexOptions.IgnoreCase); List<string> data = new List<string> { "The child wanted to play in the mud", "Hi there", "Hector had a hip problem" }; var filtered = data.Where(d => re.IsMatch(d));

DotNetFiddle Example

over 4 years ago · Santiago Trujillo Report

0

You could split your sentence into words - you could split at each space and then trim any punctuation. Then check if any of these words are 'hi':

var punctuation = source.Where(Char.IsPunctuation).Distinct().ToArray();
var words = sentence.Split().Select(x => x.Trim(punctuation));
var containsHi = words.Contains("hi", StringComparer.OrdinalIgnoreCase);

See a working demo here: https://dotnetfiddle.net/AomXWx

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!