2

I am a beginner in both, Java and regular expressions. I want to get a name as an input, by which I mean that only names that have English alphabets A-Z, case insensitive and spaces.

I am using a Scanner class to get my input but my code doesn't work. It looks like:

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();

I checked my regular expression on the website regex101.com and found out that it works fine.

For example, If I input it my name, Akshay Arora , the regex site says it is okay but my program prints

That's not a name
That's not a name

Same line is printed twice and it again asks me for input. Where am I going wrong?

Pshemo
  • 113,402
  • 22
  • 170
  • 242
Akshay Arora
  • 1,833
  • 1
  • 9
  • 28

2 Answers2

2

Two parts are wrong:

  • $ and ^ anchors are considered in the context of entire input, not in the context of the next token. It will never match, unless the input has a single line that matches the pattern in its entirety.
  • You use default delimiters, which include spaces; therefore, Scanner will never return a token with a space in it.

Here is how you can fix this:

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();

Demo.

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
1

Here its sample program related to 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");

    }
}

Hope this will help you

Vignesh Shiv
  • 1,079
  • 7
  • 20