kashif4u
kashif4u

Reputation: 175

Exact/Literal word or pattern match regex

I am trying to match the patterns in a table with user utterance.

string userUtterance = "I want identification number for number of customers";

string pattern1 = "identification number";

string pattern2 = "tom";

string pattern3 = "id"; 

Desired results:

bool match1  =  regex.Ismatch(userUtterance, pattern1); // should match

if(match1 == true)
{
    // replace only the matched pattern in userUtterance
};

bool match2  =  regex.Ismatch(userUtterance, pattern2); // should not match

bool match3  =  regex.Ismatch(userUtterance, pattern3); // should not match

I would like a little advice on the use of regular expressions matching that syntax to restrict ambiguous matches and exactly match the literal words.

Thanks

Upvotes: 2

Views: 11973

Answers (2)

user2140261
user2140261

Reputation: 7993

Instead of regex for the replacing you could just try this:

        string userUtterance = "I want identification number for number of customers";

        string pattern1 = "identification number";

        string pattern2 = "\btom \b";

        string pattern3 = "\bid \b";

        string replacement = "{YourWordHere}"

        string newuserUtterance = userUtterance.Replace(pattern1, replacement );

        bool match2 = Regex.IsMatch(newuserUtterance, pattern2); // should not match

        bool match3 = Regex.IsMatch(newuserUtterance, pattern3); // should not match

This will replace pattern1 in the string userUtterance with your replacement

then test if the tom <= Note the space, is in the newly created string, then it will test if id <= again note the space, is in the new string.

Upvotes: 0

pid
pid

Reputation: 11597

You can use the anchor \b for word boundaries:

"\bonly these words\b"

This will match only these words in these sentences:

Here are only these words baby.

Here are "only these words" baby.

Here are only these words, baby.

Here are only these words.

I said: 'only these words'.

Upvotes: 6

Related Questions