我有一个名字字段,我必须针对一个应该只接受字母和空格的正则表达式进行验证。我可以获得相同的正确运行代码。
我基本上需要检查字符串是否与模式匹配。
所以,如果我输入“rahul bose”,它应该返回true,但如果我输入“rahul-bose”或“rahul bose 9”,它应该返回false。
我试过这样的事情,但总是失败
package pckg;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TextRegex {
private String name;
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public boolean checkError(String name){
String regex = "[A-Za-z]";
if(Pattern.matches(regex, name))
return true;
return false;
}
public static void main(String[] arg){
TextRegex textRegex = new TextRegex();
textRegex.setName("nayanava");
System.out.println(textRegex.checkError(textRegex.getName()));
}
}