【问题标题】:How to validate EditText input with a custom regex in Android?如何在 Android 中使用自定义正则表达式验证 EditText 输入?
【发布时间】:2016-06-28 12:35:39
【问题描述】:

我是 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 个字符必须是字符。那么我该如何实施呢?

【问题讨论】:

  • 数字和数字是一回事,请解释一下
  • 你要匹配什么样的字符串?
  • 旁注:你应该检查一个变量是否为空之前调用它的方法。
  • @cricket_007 复制那个,会起作用的。谢谢:)

标签: java android regex validation


【解决方案1】:

根据正则表达式检查输入的通用模式:

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

【讨论】:

  • 哇。感谢您回复我的解决方案。我现在正在努力。会让你知道它是怎么回事:D
  • 感谢您的帮助。根据您的示例大致了解它的工作原理,是的,它正在工作! :D
猜你喜欢
  • 2015-01-31
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 2016-02-26
相关资源
最近更新 更多