RKh
RKh

Reputation: 14161

Regular expressions match not working accurately with semicolon

I have a string of codes like:

0926;0941;0917;0930;094D;

I want to search for: 0930;094D; in the above string. I am using this code to find a string fragment:

   static bool ExactMatch(string input, string match)
    {

        return Regex.IsMatch(input, string.Format(@"\b{0}\b", Regex.Escape(match)));

    }

The problem is that sometimes the code works and sometimes not. If I match a single code for example: 0930; , it works but when I add 094D; , it skips match.

How to refine the code to work accurately with semicolons?

Upvotes: 0

Views: 563

Answers (3)

rikitikitik
rikitikitik

Reputation: 2450

"\b" denotes a word boundary, which is in between a word and a non-word character. Unfortunately, a semi-colon is not a word character. There is no "\b" at the end of "0926;0941;0917;0930;094D;" thus the Regex shows no match.

Why not just remove the last "\b" in your Regex?

Upvotes: 1

Andy
Andy

Reputation: 1080

Perhaps I'm not understanding your situation correctly; but if you're looking for an exact match within the string, couldn't you simply avoid regex and use string.Contains:

static bool ExactMatch(string input, string match)
{
    return input.Contains(match);
}

Upvotes: 0

Thit Lwin Oo
Thit Lwin Oo

Reputation: 3438

Try this, I have tested..

string val = "0926;0941;0917;0930;094D;";
string match = "0930;094D;"; // or match = "0930;" both found

if (Regex.IsMatch(val,match))
     Console.Write("Found");
else Console.Write("Not Found");

Upvotes: 1

Related Questions