Java Regular Expression match leading capital letter

Introduction

To match characters that does not have a predefined character class, use square brackets,[].

For example, the pattern "[aeiou]" matches a single character that's a vowel.

Character ranges are represented by placing a dash (-) between two characters.

In the example, "[A-Z]" matches a single uppercase letter.

"[A-Za-z]" matches all uppercase and lowercase letters.

"[A-Z][a-zA-Z]*" matches at least one capital letter.

"[A-z]" matches all letters and also matches those characters (such as [ and \) with an integer value between uppercase Z and lowercase a.

The asterisk after the second character class indicates that any number of letters can be matched.

The first letter must be capital and followed by upper case or lower case letters.

public class Main {
  // execute application
  public static void main(String[] args) {
    String s = "Java";

    boolean b = s.matches("[A-Z][a-zA-Z]*");
   /*from   w w  w  .j  a v  a2  s  . c om*/
    System.out.println(b);

  }
}



PreviousNext

Related