java 如何在 Android 中使用自定义正则表达式验证 EditText 输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35971163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:49:44  来源:igfitidea点击:

How to validate EditText input with a custom regex in Android?

javaandroidregexvalidation

提问by topacoBoy

I am new to android development and also regular expression. I am able to retrieve inputs from user through the EditText and check if it's empty and later display the error message if it is empty but I am not sure on how to check with a custom regex. Here's my code :

我是 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}

So, im expecting the user to input a 5 character long string where the first 2 letters must be numbers and the last 3 characters must be characters. So how can i implement it people ?

所以,我希望用户输入一个 5 个字符长的字符串,其中前 2 个字母必须是数字,最后 3 个字符必须是字符。那么我怎样才能实现它呢?

回答by Mattias Isegran Bergander

General pattern to check input against a regular expression:

根据正则表达式检查输入的一般模式:

String regexp = "\d{2}\D{3}"; //your regexp here

if (myInput_Input_a.matches(regexp)) {
    //It's valid
}

The above actual regular expression assumes you actually mean 2 numbers/digits (same thing) and 3 non-digits. Adjust accordingly.

上面的实际正则表达式假设您实际上是指 2 个数字/数字(相同的东西)和 3 个非数字。相应调整。

Variations on the regexp:

正则表达式的变化:

"\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