Is there an elegant way to execute partial regular expressions in Java?

I need to check if a given string matches a partially specified regular expression. For example, for regex, the ab[0-9]cstrings "a", "ab", "ab3" and "b3c" will "match", but not the strings "d", "abc" or "a3c". What I did was clumsy a(?:b(?:[0-9](?:c)?)?)?(which only works for partial matches, in particular those that “start” to match), but since this is part of the API, I would better give users a more intuitive way to enter their matching regular expressions.

In case the description is not very clear (and I understand that this may not be so!), This will be used to check text input in text fields. I want to prevent any editing that will result in an invalid string, but I can't just match the string to a regular regex, since until it is fully entered, it will not match. For example, using the regex above ( ab[0-9]c) when I try to type "a", it is not allowed because the string "a" does not match the regular expression.

Basically, it's a kind of converse startsWith()that works with regular expressions. ( new Pattern("ab[0-9]c").startsWith("ab3")must return true.)

Any ideas?

+5
source share
3

Matcher.hitEnd() , ?

Pattern thePattern = Pattern.compile(theRegexString);
Matcher m = thePattern.matcher(theStringToTest);
if (m.matches()) {
    return true;
}
return m.hitEnd();
+6

, - , , , . , .

, , . ?

+4

, :

^(?:a|b|[0-9]|c|ab|b[0-9]|[0-9]c|ab[0-9]|b[0-9]c|ab[0-9]c)?$

, , , . 4 (a, b, [0-9] c), OR 4 + 3 + 2 + 1 = 10 . ( n (n × (n + 1))/2 ). , . - (, ) .

The best solution is probably to have a message next to the input field telling the user "not enough information" or something else, and when he has this right, change it to a green flag or something else. Here's a recent article from A List Apart that weighs the pros and cons of different approaches to this problem: Inline Validation in web forms .

+2
source

All Articles