我是Android开发和正则表达的新手。我能够通过EditText从用户检索输入并检查它是否为空,如果它为空,则稍后显示错误消息,但我不确定如何检查自定义正则表达式。这是我的代码:
myInput = (EditText) findViewById(R.id.myInput);
String myInput_Input_a = String.valueOf(myInput.getText());
//replace if input contains whiteSpace
String myInput_Input = myInput_Input_a.replace(" ","");
if (myInput_Input.length()==0 || myInput_Input== null ){
myInput.setError("Something is Missing! ");
}else{//Input into databsae}
所以,我希望用户输入一个5个字符长的字符串,其中前2个字母必须是数字,最后3个字符必须是字符。那我该如何实现呢?
答案 0 :(得分:8)
根据正则表达式检查输入的一般模式:
String regexp = "\\d{2}\\D{3}"; //your regexp here
if (myInput_Input_a.matches(regexp)) {
//It's valid
}
上面的实际正则表达式假定您实际上意味着2个数字/数字(相同的东西)和3个非数字。相应调整。
正则表达式的变化:
"\\d{2}[a-zA-Z]{3}"; //makes sure the last three are constrained to a-z (allowing both upper and lower case)
"\\d{2}[a-z]{3}"; //makes sure the last three are constrained to a-z (allowing only lower case)
"\\d{2}[a-zåäöA-ZÅÄÖ]{3}"; //makes sure the last three are constrained to a-z and some other non US-ASCII characters (allowing both upper and lower case)
"\\d{2}\\p{IsAlphabetic}{3}" //last three can be any (unicode) alphabetic character not just in US-ASCII