Skip to content

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

Leave a Reply

Your email address will not be published.