Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to find word in string without split

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.

like image 424
Edgar Avatar asked Sep 15 '12 17:09

Edgar


2 Answers

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
like image 114
Brenda Bell Avatar answered Oct 19 '22 15:10

Brenda Bell


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);
    }
  }
}
like image 30
Jignesh Thakker Avatar answered Oct 19 '22 17:10

Jignesh Thakker