-3 java regex android pattern-matching
在我的 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();
}
}
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
满足 3 个字符长的条件并正常工作,但检查字符串是否在字母表中的条件不起作用。
您可以使用正则表达式,[A-Za-z]{3}或者\p{Alpha}{3}指定 3 个字母。在Quantifiers了解更多信息。
这也将帮助您合并以下两个if条件
String regex = "...";
String regex1 = "[a-zA-Z].";
if(Pattern.matches(regex,gstin)) {
if (Pattern.matches(regex1,gstin)) {
Run Code Online (Sandbox Code Playgroud)
如下图所示:
String regex = "[A-Za-z]{3}";// "\\p{Alpha}{3}"
if(Pattern.matches(regex,gstin)) {
Run Code Online (Sandbox Code Playgroud)
您当前的正则表达式[a-zA-Z].指定一个字母表,指定[a-zA-Z]后跟任何单个字符,指定一个点(即.)。
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |