String.startsWith() / endsWith() / matches()
Methods for checking whether a string starts or ends with a specific string, or whether it matches a regular expression pattern. They are widely used for input validation and conditional branching.
Syntax
// Checks whether the string starts with the specified prefix. str.startsWith(String prefix); str.startsWith(String prefix, int toffset); // Checks whether the string ends with the specified suffix. str.endsWith(String suffix); // Checks whether the string matches the specified regular expression pattern. str.matches(String regex);
Method List
| Method | Description |
|---|---|
| startsWith(String prefix) | Returns true if the string starts with the specified prefix, or false otherwise. |
| startsWith(String prefix, int toffset) | Returns whether the substring starting at the specified offset matches the prefix. |
| endsWith(String suffix) | Returns true if the string ends with the specified suffix, or false otherwise. |
| matches(String regex) | Returns true if the entire string matches the regular expression pattern. Returns false for partial matches. |
Sample Code
// Use startsWith() to check the beginning of a string.
String url = "https://wp-p.info";
System.out.println(url.startsWith("https")); // Prints: true
System.out.println(url.startsWith("http://")); // Prints: false
// Use endsWith() to check a file extension.
String filename = "photo.jpg";
System.out.println(filename.endsWith(".jpg")); // Prints: true
System.out.println(filename.endsWith(".png")); // Prints: false
// Use matches() to check whether a string contains only digits.
String num = "12345";
System.out.println(num.matches("[0-9]+")); // Prints: true
// matches() can also be used for email address validation.
String email = "user@example.com";
System.out.println(email.matches("^[\\w.+-]+@[\\w-]+\\.[\\w.]+$")); // Prints: true
// Example of using startsWith() with an offset.
String str = "JavaProgramming";
System.out.println(str.startsWith("Pro", 4)); // Prints: true
Notes
startsWith() and endsWith() check whether the beginning or end of a string matches the specified string, respectively. They are well suited for simple conditional checks such as URL scheme detection and file extension validation.
matches() checks whether the entire string matches a regular expression. Because matches() matches against the full string, you need to include wildcards (such as .*) in your pattern if you want partial matching. Also, because the pattern is compiled on every call, consider using Pattern.compile() to reuse a compiled pattern when calling it repeatedly.
To search within a string, use indexOf() / contains(). To replace parts of a string, use replace() / replaceAll().
If you find any errors or copyright issues, please contact us.