Determining if a string is an exact match to regex

G

Guest

At the first glance, this problem seems to be easy, but I found it not:
There is a regex, that is known to be valid, but of which I have no control
(in comes from a public XML schema). I need to evaluate an input string to
make sure it matches the regex.
The most obvious code apprears to be something like this (as Regex class
only has substring search methods, and no exact match methods):

Match m = myRegex.Match(inputString);
if (m.Success && m.Length == inputString.Length)
{
// Some code...
}

However, there is a problem. For example, if the regex is "a|ab", the input
string "ab" should match it, but is will fails the above test (because
higher-priority substring "a" will be matched).
Currently, I can find no fix/workaround: since modifying regex is not an
option changing "a|ab" to "ab|a" is not an acceptable solution. Also, the
code must be generic with regard to regex, so inserting ||inputString=="ab"
into the 'if' statement is not an acceptable solution either.

Can anyoune suggest a way to
 
G

Guest

This workaround code seems to cover all the cases that I've tried. It does
modify regex, but it's a generic modification that makes not assumption about
the content of regex:

Regex myRegex2 = "\\A(?:" + myRegexPatternStr + ")\\z";
if (myRegex2.IsMatch(inputString))
{
// Some code...
}

Essentially, this code modifies every incoming regex so that it will only
match substrings that take up the whole input str.
 
J

John Griffiths

Assuming you are using "Microsoft VBScript Regular Expressions x.x" (1.0 and
5.5).

Does the RegExp2.Test() method work as advertised?

RegExp2.Pattern = "a|ab"
If RegExp2.Test("ab") Then
' stuff
End if

Not sure of "|" in MS regex expressions.

Regards John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top