I have some strings:
"rose with ribbon"
"roses in concrete"
"roses on bed"
I have to write a program to find string where preffered word exists
E.g: find string where "on" is, so I need to get only "roses on bed".
I used this code:
foreach (KeyWord key in cKeyWords)
{
foreach (string word in userWords)
{
if (key.keyWord.IndexOf(word) != -1)
{
ckeyList.Add(key);
}
}
}
but I get all strings because IndexOf finds "on" in all of them.
Is there any other solution to find separate word in string without splitting? Maybe it is possible to use Linq or Regex? but I'm not good at using them so would be nice to have any examples.
Using regex with \bon\b
should do it.
\b
is the regex anchor for word boundary, so that regex will match a word boundary immediately followed by on
immediately followed by another word boundary.
The following C# example...
string[] sArray = new string[] { "rose with ribbon", "roses on bed", "roses in concrete" }; Regex re = new Regex("\\bon\\b"); foreach (string s in sArray) { Console.Out.WriteLine("{0} match? {1}", s, re.IsMatch(s)); Match m = re.Match(s); foreach(Group g in m.Groups) { if (g.Success) { Console.Out.WriteLine("Match found at position {0}", g.Index); } } }
... will generate the following output:
rose with ribbon match? False roses on bed match? True Match found at position 6 roses in concrete match? False
Yes, By using Regex you can find word in string. Try With,
string regexPattern;
foreach (KeyWord key in cKeyWords)
{
foreach (string word in userWords)
{
regexPattern = string.Format(@"\b{0}\b", System.Text.RegularExpressions.Regex.Escape(word));
if (System.Text.RegularExpressions.Regex.IsMatch(key.keyWord, regexPattern))
{
ckeyList.Add(key);
}
}
}
Use ToLower() method on string if you don't want to consider with case sensitive.
foreach (KeyWord key in cKeyWords)
{
foreach (string word in userWords)
{
regexPattern = string.Format(@"\b{0}\b", System.Text.RegularExpressions.Regex.Escape(word.ToLower()));
if (System.Text.RegularExpressions.Regex.IsMatch(key.keyWord.ToLower(), regexPattern))
{
ckeyList.Add(key);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With