我想创建一个程序,该程序能够检查字符串是否有效作为人名。但是我正在努力使用正则表达式来验证字符串是否可以接受为人名。你能帮我在我的代码中实现正确的条件吗?如果满足以下条件,字符串将被视为人名:
- 第一个单词前没有空格
- 没有非单词字符
- 没有 2 个或更多个连续空格
我还想删除一个空格,如果它存在于我的字符串中的最后一个单词之后。我所做的所有这些只是为了强制用户输入正确的文本格式,我很快就会将其发布到我的 JSON 上。这就是为什么一切都应该首先进行验证的原因。空格没问题,因为我已经在我的 XML 文件中定义了正确的 EditText 输入类型。
这是我尝试实现的代码:
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
}
如果您有任何疑问,请随时提出。
关于java - 如何使用 java 正则表达式验证字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26622157/