Regex - Starts With to Match the Beginning of String
In this short tutorial, we are going to cover in-depth the anchor starts with to match the start of a string using regex.
First, we will explain what the anchor ^ means. Then, we are going to illustrate how to find a string that does not start with a specific character.
Anchor Starts With in Regular Expression
The caret ^ is the anchor that matches the beginning of a string in regular expressions.
For instance, the regex “^abc” denotes a string that begins with the word abc.
Similarly, the pattern “^abc.*” matches a string that starts with abc followed by any character (.), any number of times (*).
Regex to Match the Beginning of String
As we mentioned earlier, we use the caret anchor to match the position before the first character in a given string.
For example, compiling the regex “^a” against “azh” will match “a”. However, the pattern “^z” does not match anything since the string does not start with “z”.
Regex Example | Description |
^dev | matches any string that starts with "dev" |
^dev.*us$ | matches any string starting with "dev" and ends with "us" |
^[0-9] | matches strings beginning with a number |
^abc\s | matches a string that starts with "abc" followed by a space |
Now, let’s see how we can use the anchor ^ in Java to check the beginning of a string:
public static void main(String[] args) {
Pattern.compile("^dev")
.matcher("devwithus.com")
.find(); // true
Pattern.compile("^[0-9]")
.matcher("2d position")
.find(); // true
Pattern.compile("^dev.*net$")
.matcher("devwithus.com")
.find(); // false
Pattern.compile("^dev\s", Pattern.CASE_INSENSITIVE)
.matcher("DEV withus.com")
.find(); // true
}
As we can see, we used the Pattern.CASE_INSENSITIVE flag to enable case insensitivity.
Regex - Does Not Start With
There are several ways to check whether a string does not start with particular characters.
Typically, we can use a negative lookahead assertion “(?!)” to achieve this. For example, the pattern “^(?!dev)” means a string that does not begin with dev.
Pattern.compile("^(?!dev)")
.matcher("devwithus.com")
.find(); // false
Alternatively, using the anchor ^ inside brackets [] denotes a regex that means any character except those specified in the brackets.
For instance, the pattern “[^a-z]” matches any string that does not start with a lowercase character.
Pattern.compile("^[^a-z]")
.matcher("1a2b3c")
.find(); // true
Pattern.compile("^[^\\d]")
.matcher("azhwani")
.find(); // true
Conclusion
In this tutorial, we have highlighted the use of the anchor caret ^ that denotes the “starts with” pattern.
Along the way, we have seen how to match the beginning of a string using regular expressions.
Lastly, we demonstrated how to find a string that does not start with specific characters.