问题描述
在我的 Android 应用程序中,我需要验证用户输入的字符串只有 3 个字符长,并且只有字母表中的字符。
满足 3 个字符长的条件并正常工作,但检查字符串是否在字母表中的条件不起作用。 我附上了下面的代码。
public class MainActivity extends AppCompatActivity {
EditText etGSTIN ;
Button btVerify ;
TextView tvstateName ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etGSTIN = findViewById(R.id.etGSTIN);
btVerify = findViewById(R.id.btVerify);
tvstateName = findViewById(R.id.btStateName);
btVerify.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String gstin = etGSTIN.getText().toString().trim();
String regex = "...";
String regex1 = "[a-zA-Z].";
Log.d("Entered in Oclick","Entered in OnClick()");
if(Pattern.matches(regex,gstin)){
Log.d("ENterd in First if","MEssage");
if (Pattern.matches(regex1,gstin)) {
Log.d("Entered in nested If","Entered in nested IF");
Toast.makeText(MainActivity.this,"Verified GSTIN",Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
更新查询已解决: 这个问题现在已经解决了,因为我使用了 string string regex 作为 regex1 。这就是为什么,它没有给出任何结果。
解决方法
满足 3 个字符长的条件并且工作正常,但是 检查字符串是否在字母表中的条件是 不工作。
您可以使用指定 3 个字母的正则表达式 [A-Za-z]{3}
或 \p{Alpha}{3}
。在 Quantifiers 上了解更多信息。
这也将帮助您合并以下两个 if
条件
String regex = "...";
String regex1 = "[a-zA-Z].";
if(Pattern.matches(regex,gstin)) {
if (Pattern.matches(regex1,gstin)) {
如下图所示:
String regex = "[A-Za-z]{3}";// "\\p{Alpha}{3}"
if(Pattern.matches(regex,gstin)) {
您当前的正则表达式 [a-zA-Z].
正在指定单个字母表,指定为 [a-zA-Z]
后跟任何单个字符,指定为点(即 .
)。
使用 ^[a-zA-Z]*$
作为您的第二个正则表达式。 ^
匹配字符串的开头,[a-zA-Z]
匹配任何字母字符,*
是匹配前面标记(任何字母字符)零次或多次的量词,{{ 1}} 匹配字符串的结尾(因此它检查字符串中的所有字符是否满足条件)。
您当前的正则表达式 $
首先匹配任何字母字符,然后 [a-zA-Z].
匹配任何字符,然后匹配任何字母字符和任何字符(因此总共需要 2 个字符)。