I don't think lookingAt()
is the correct model for what you're trying to do. All it does is anchor the match to the beginning of the input, as if you had used the ^
start anchor at the beginning of your regex and called find()
, and that would be trivial to emulate in .NET.
I think what you're trying to do is prevent users from entering invalid data. For example, if a textfield expects a decimal number with two decimal places, your validation regex might be \d+\.\d\d
. If a user starts by typing a digit, the regex doesn't match, but the digit could be part of a valid entry, so you let them keep on typing. But if the user types 'z', you block it because there's no way it could be part of a valid entry.
In other words, you don't want to know if the regex matches part of the string, you want to know if the string matches part of the regex. There is a way to do that in Java, using the hitEnd()
method, but I don't think .NET has an equivalent for that. In fact, I don't know of any other regex flavor that does.
But blocking users' keypresses is rather rude anyway, in my opinion. I prefer to let them know by some other means that their input is invalid. For example, you can display the contents of the textfield in red, or disable the button that they use to submit the entry (or both). Each time something changes in the textfield, you check the contents against your (full) regex and update the state of the field and/or button accordingly.
Here's demonstration of hitEnd()
:
import java.util.regex.*;
public class Test
{
public static void main(String[] args) throws Exception
{
Pattern p = Pattern.compile("\\d+\\.\\d\\d");
Matcher m = p.matcher("");
String[] tests = { "5.99", "5", "@" };
for (String s : tests)
{
if (m.reset(s).matches())
{
System.out.println("full match");
}
else if (m.hitEnd())
{
System.out.println("partial match");
}
else
{
System.out.println("no match");
}
}
}
}
I get "full match" for the first string, "partial match" for the second, and "no match" for the third.