Java Regular Expression match leading numbers

Description

Java Regular Expression match leading numbers

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

    boolean b = s.matches("\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
   /*  ww  w  .java  2  s  .co  m*/
    System.out.println(b);

  }
}

The first character class matches any digit one or more times (\\d+).

Two \ characters are used, because \ normally starts an escape sequence in a string.

So \\d in a String represents the regular-expression pattern \d.

Then we match one or more white-space characters (\\s+).

The character "|" matches the expression to its left or to its right.

For example, "Hi (CSS|HTML)" matches both "Hi CSS" and "Hi HTML".

The parentheses are used to group parts of the regular expression.

In this example, the left side of | matches a single word, and the right side matches two words separated by any amount of white space.

So the address must contain a number followed by one or two words.




PreviousNext

Related