我正在尝试使用TextWatcher和regex来验证用户输入。请注意,我有一个复杂的正则表达式:
edit.addTextChangedListener(new TextWatcher() {
private final Pattern m_regex = Pattern.compile("([a-zA-Z]{4}[ ]{0,1}){7}");
@Override
public void afterTextChanged(Editable s) {
String text = s.toString();
int length = text.length();
if(!m_regex.matcher(text).matches() && length > 0) {
s.delete(length - 1, length);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
这里的问题是匹配器只能检查2个字符串状态:匹配并且与提供的表达式不匹配,但是对于输入验证,还需要检查中间状态 - 当字符串与模式不匹配但不是也与之相矛盾。有没有办法可以使用我的正则表达式来验证EditText
中输入的字符串?
答案 0 :(得分:1)
与另一个正则表达式进行匹配。很抱歉,如果答案看起来很愚蠢,但正如您之前所说, matcher只能检查2个字符串状态:匹配且不匹配。
编辑:
我更了解你的问题。你可以这样做:测试输入与这个正则表达式
^(([a-zA-Z]{4}[ ]{0,1}){0,6}([a-zA-Z]{0,4})|([a-zA-Z]{4}))$
这将验证文本是否已插入。如果没问题,请让用户继续。只有在用户输入完文本后才能使用正则表达式! -
或者,如果你想检查用户是否已完成写操作:匹配我写的正则表达式以查看文本是否正确。如果确定匹配你的,如果匹配,则用户已完成插入文本。