在java中使用正则表达式获取名称作为输入

在java中使用正则表达式获取名称作为输入,java,regex,Java,Regex,我是Java和正则表达式的初学者。我想得到一个名字作为输入,我的意思是只有英文字母a-Z,不区分大小写和空格的名字 我正在使用Scanner类获取输入,但我的代码不起作用。它看起来像: Scanner sc= new Scanner(System.in); String n; while(!sc.hasNext("^[a-zA-Z ]*$")) { System.out.println("That's not a name!"); sc.nextLine(); } n = sc

我是Java和正则表达式的初学者。我想得到一个名字作为输入,我的意思是只有英文字母a-Z,不区分大小写和空格的名字

我正在使用
Scanner
类获取输入,但我的代码不起作用。它看起来像:

Scanner sc= new Scanner(System.in);
String n;

while(!sc.hasNext("^[a-zA-Z ]*$"))
{
    System.out.println("That's not a name!");
    sc.nextLine();
}
n = sc.next();
我在网站上查看了我的正则表达式,发现它工作得很好

例如,如果我输入它我的名字,
Akshay Arora
,regex站点会说没问题,但我的程序会打印出来

That's not a name
That's not a name
同一行打印了两次,它再次要求我输入。我哪里做错了

有两部分是错误的:

  • $
    ^
    锚定在整个输入的上下文中考虑,而不是在下一个标记的上下文中考虑。它永远不会匹配,除非输入有一行与整个模式匹配
  • 使用默认分隔符,包括空格;因此,
    Scanner
    永远不会返回带有空格的令牌
以下是解决此问题的方法:

Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
String n;

while(!sc.hasNext("[a-zA-Z ]+"))
{
    System.out.println("That's not a name!");
    sc.nextLine();
}
n = sc.next();

这里是与regex相关的示例程序

public class Program {

    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String inputName = sc.next();

    String regex = "^[a-zA-Z ]*$";
    // Compile this pattern.
    Pattern pattern = Pattern.compile(regex);

    // See if this String matches.
    Matcher m = pattern.matcher(inputName);
    if (m.matches()) {
        System.out.println("Valid Name");
    } else
        System.out.println("Invalid Name");

    }
}

希望这将对您有所帮助。

。匹配(regex)
是您想要做的!我指的是:您的扫描仪对象也是
abc1
而不是
sc
。还有
scanner.hasNext()
返回布尔值。@UmaKanth,第三个元音示例是这样使用正则表达式的。我在顶部定义了一个scanner对象
sc
,只是我的错误,我把
abc1
留下了。应该删除,太好了。这回答了问题所在的上下文。值得一提的是,此模式允许任意数量的空格,不适合进行名称检查