-2

I have the folowing code in Java

 Pattern pattern = Pattern.compile("[a-zA-Z]+", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher("1A");
    boolean matchFound = matcher.find();
    if(matchFound) {
      System.out.println("Match found");
    } else {
      System.out.println("Match not found");
    }

The result of that says that 1A match the regex "[a-zA-Z]+".

I only need to accept words starting with a letter.

I did the same in question.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Armando
  • 7
  • 1
  • 3
    Use _[Matcher#matches](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/regex/Matcher.html#matches())_ instead of _[Matcher#find](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/regex/Matcher.html#find())_, and at that rate just use _[String#matches](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/String.html#matches(java.lang.String))_. – Reilas Aug 22 '23 at 19:38
  • The Matcher class has many methods. If you had printed out `matcher.start()`, your issue would have been clear. And reading the documentation of Matcher also would have helped you. – VGR Aug 23 '23 at 13:51

2 Answers2

2

matcher.find() finds matches within the input; in your case it matches A.

You want:

"1A".matches("[a-zA-Z].*")

String#matches() must match the entire String to return true (so no need for ^ at the start), and the regex requires that the first character be a letter (the remaining characters, if any, can be anything).

Bohemian
  • 412,405
  • 93
  • 575
  • 722
-1

The given RegEx [a-zA-Z]+ matches a character irrespective of its position in the string. Here 1A is also a match.

If you want to match words starting with a letter use "^" at the beginning of the regex. "^" is identify starting of the string.

and to match zero or more letters you can use [a-zA-Z]*, your final regEx looks like this.

exp - "^[a-zA-Z][a-zA-Z]*"

  • I'd like to note that you're correct, except for the addition of the _[a-zA-Z]*_. Since they're looking to assert that the first character is a letter, just use _^[a-zA-Z]_. – Reilas Aug 23 '23 at 01:19