Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a string between another string?

Tags:

string

c#

regex

I am developing an ASP.NET application in which I have to display description for text documents after performing SQL full text search query. I have to highlight the user input search string with in description of that document. Now problem is that:

If the user enters rang as input search string then I have to check whether that string is part of another word or appears as an individual word. For example:

1 - rang may appear by itself or it may be part of some word i.e. W*rang*ling.

2 - weep may appear by itself or it may be part of *weep*ing.

How can I validate such condition for strings? Is it possible through Regex.Match()? Any help will be much appreciated.

NOTE: A single word may appear multiple times in multiple ways within a paragraph.


1 Answers

You can do that in regex

string word=Regex.Escape("rang");//your word..used regex.escape to escape regex characters if any

Regex rx = new Regex("\b(.*?)"+word+"(.*?)\b", RegexOptions.IgnoreCase);

foreach (Match m in rx.Matches(yourInputText))
{
    if(m.Groups[1]!="" || m.Groups[2]!="")
    {
        //the word is between some words
    }
    else
    {
        //the word occurs separately
    }
}
like image 111
Anirudha Avatar answered Jul 04 '26 03:07

Anirudha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!