Java RegEx – Matching at Beginning and End of the string

Java RegEx – Matching at Beginning and End of the string example shows how to match a pattern at the beginning (start) or at the end of the string content.

How to match at the beginning of the string using regex in Java?

Consider below given code example, where we want to extract a number from the string content.

Output

As you can see from the output, the pattern matched with two numbers in the string content, one at the start of the string (i.e. 4), and another at the end of the string (i.e. 2). But what if you only want the number specified at the start?

In that case, you can specify the caret character (“^”) at the start of the pattern like given below.

Here, the caret symbol specifies the start of the string. Let’s run our example with the new pattern.

Output

As you can see from the output, this time our pattern matched the only number that is specified at the start of the string content.

How to match at the end of the string using regex in Java?

The dollar sign (“$”) is used to specify the end of the string content in the regex pattern. So in above given example, to match a number at the end of the string content, the pattern will be as follows.

Here, the number must be followed by the end of the string. Let’s run our example with this pattern.

Output

As you can see from the output, the only number that was matched by our pattern was specified at the end of the string (i.e. 2).

If you want to learn more about regex patterns, please visit the Java regex tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *