I developed a class that should extend javafx.scene.control.TextField
and should verify the input against an arbitrary regular expression.
The next feature to implement is that the text-field should switch focus to the next control element if no additional input could be added to the actual input without giving an invalid input.
For me this boils down to:
I have a string called A
.
I have a regular expression p
.
I should find out if there is a character c
so that p(A+c)
is true assuming that p(A)
is true.
I found this Question leading to the requireEnd method of java.util.regex.Matcher
, but this method only tells me if there is a character c
so that p(A+c)
is false assuming that p(A)
is true.
My next approach was to simply loop over all characters, append them and test for a partial match using Matcher.hitEnd
. This works but it requires 1.1 million chars to be tested each time to fit to unicode standard.
So I m looking for an efficient way to implement the following (shortened) class:
public class AdvancedMatcher{
Pattern p;
Matcher m;
String actInput; /**< The actual input string */
static final int MAX_UNICODE=0x10FFFF;
public AdvancedMatcher(String regexp){
p = Pattern.compile(regexp);
m = p.matcher("");
}
public void reset(String input) {
m.reset(input);
actInput=input;
}
/**
* This method should check if the actual input is a positive match to the regular expression
* and no character could be appended to the actual input without turning the positive match
* into a negative match.
*
* If the actual input is not a match to the regular expression of this instance this
* method should return false.
*
* Otherwise false is returned if a character is found that could be appended to the regular
* expression without turning it into a negative match.
*
* @return false if actual input is a negative match or if an additional {@link Character}
* exists that would not turn it into a negative match.
*/
public boolean requireEnd() {
//To be clear, "return m.requireEnd();" does not solve this problem
if(!m.matches())
return false;
for(int i=0;i<MAX_UNICODE;++i) {
Matcher tmpM=p.matcher(actInput+String.valueOf(Character.toChars(i)));
if(tmpM.matches() || tmpM.hitEnd())
return false;
}
return true;
}
}