Java start end of string
In Java regular expressions, you can use ^
to match the start of a string and $
to match the end of a string.
^
matches the start of a string, so if you place it at the beginning of a regular expression, the regular expression will only match if the input string starts with the specified pattern.
$
matches the end of a string, so if you place it at the end of a regular expression, the regular expression will only match if the input string ends with the specified pattern.
Here are a few examples:
// Match a string that starts with "Hello" String input1 = "Hello world"; boolean matches1 = input1.matches("^Hello.*"); System.out.println(matches1); // true // Match a string that ends with "world" String input2 = "Hello world"; boolean matches2 = input2.matches(".*world$"); System.out.println(matches2); // true // Match a string that starts with "Hello" and ends with "world" String input3 = "Hello world"; boolean matches3 = input3.matches("^Hello.*world$"); System.out.println(matches3); // true
In the first example, the regular expression ^Hello.*
matches a string that starts with "Hello" followed by any number of characters.
In the second example, the regular expression .*world$
matches a string that ends with "world" preceded by any number of characters.
In the third example, the regular expression ^Hello.*world$
matches a string that starts with "Hello" followed by any number of characters and ends with "world".