Partial Match with a .NET regular expression

  • Thread starter Thread starter Christian Staffe
  • Start date Start date
C

Christian Staffe

Hi,

I would like to check for a partial match between an input string and a
regular expression using the Regex class in .NET. By partial match, I mean
that the input string could not yet be complete but I want to know if a
match is possible so far.

For instance I want to design a text box to enter a date and validate the
correctness of the date as the user types character. If the user enters
1953/12/23 it will match my regex of course but I want to check if there is
a potential match after each character is entered by the user. Trying the
match for "1", "19", "195",... 1953/12/2" should tell me that the string
doesn't match but could match ! If I try to validate "1953/16", then I would
get an error because this string will never match the regex even if it's not
yet complete.

Is there a way to do this with .NET regular expressions ?

Christian
 
Hi,

I would like to check for a partial match between an input string and a
regular expression using the Regex class in .NET. By partial match, I mean
that the input string could not yet be complete but I want to know if a
match is possible so far.

I don't thing you can use RegEx for this... A regular expression
delivers either a match or no match...
You are trying to ask "0 or 1?" with only these answers as being
valid, but also accepting "0.5!" as an answer...
 
It seems to me that you would need to write the regex to accept each
intermediate state. Here is a simplified expression that will evaluate to
true for any intermediate state of a string in the format 1234/56/78, but it
doesn't have any date validation logic built in:

^(\d(\d(\d(\d(/(\d(\d(/(\d(\d)?)?)?)?)?)?)?)?)?)?$


The key is to make sure that everything is optional, but each section can
only be matched if what must come before it is matched.

If you need to accept multiple date formats (mm/dd/yy, dd/mm/yyyy, etc.)
then you would probably just want to develop each with its own expression
and then use alternation to make one regex: <expression 1>|<expression
2>|<expression 3>...

Another possible way to do it is to use multiple expressions for the
in-between states and decide which one to use based on the length of the
input or the presence/position of certain characters. This results in
several more simple expressions, which may or may not be easier to code and
test than constructing one super-regex.

Brian Davis
www.knowdotnet.com
 
Back
Top