[英]How to validate a string using java regex?
我想創建一個程序,該程序能夠檢查字符串是否作為人名有效。 但是我正在努力使用正則表達式來驗證字符串是否可以接受為人名。 你能幫我在我的代碼中實現正確的條件嗎? 如果滿足以下條件,字符串將被視為人名:
我還想刪除一個空格,如果它存在於我的字符串中的最后一個單詞之后。 我做這一切只是為了強制用戶輸入正確格式的文本,我將很快在我的 JSON 上發布這些文本。 這就是為什么一切都應該首先被驗證的原因。 空格沒有問題,因為我已經在 XML 文件中定義了 EditText 的正確 inputType。
這是我試圖實現的代碼:
public boolean isFirstnameValid(String regex, String text){
Pattern checkRegex = Pattern.compile(regex);
Matcher regexMatcher = checkRegex.matcher(text);
while(regexMatcher.find()){
if(regexMatcher.group().length()!=0){
Log.e("searched",regexMatcher.group().trim());
}
}
return false;
// I returned false because, I'm still confused about what conditions should I implement.
}
這是實現我的實際參數的主要方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// String firstname = "Kirby Aster";
// String lastname = "Abadilla";
et =(EditText) findViewById (R.id.editText1);
b = (Button) findViewById (R.id.button1);
b.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String text = et.getText().toString();
isFirstnameValid("[A-Za-z]{1,}", text);
}
});
}
我不喜歡isFirstnameValid
方法的實現。 我認為你讓它變得有點復雜。 我會使用簡單的String.matches
來完成這項工作,例如:
public boolean isFirstnameValid(String text){
return text..matches("^([A-Za-z]+)(\\s[A-Za-z]+)*\\s?$");
}
上述正則表達式滿足您的所有條件,包括在末尾允許一個空格。 您可以考慮在每個單詞的第一個大寫字母的另一個條件(正則表達式會略有變化)。 然后像這樣調用它:
if( isFirstnameValid(text) ){
text = text.trim();
} else {
// define your failing condition here
}
如果您有任何疑問,請隨時詢問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.