Regex – Match Start or End of String (Line Anchors)

1. Line Anchors

In regex, anchors are not used to match characters. Rather they match a position i.e. before, after, or between characters. To match start and end of line, we use following anchors:

  • Caret (^) matches the position before the first character in the string.
  • Dollar ($) matches the position right after the last character in the string.

2. Regex patterns to match start of line

DescriptionMatching Pattern
Line starts with number“^\\d” or “^[0-9]”
Line starts with character“^[a-z]” or “^[A-Z]”
Line starts with character (case-insensitive)^[a-zA-Z]
Line starts with word“^word”
Line starts with special character“^[!@#\\$%\\^\\&*\\)\\(+=._-]”
import java.util.regex.Pattern;

public class Main {
	public static void main(String[] args) 
	{
		System.out.println(Pattern.compile("^[0-9]").matcher("1stKnight").find());

		System.out.println(Pattern.compile("^[a-zA-Z]").matcher("FirstKnight").find());

		System.out.println(Pattern.compile("^First").matcher("FirstKnight").find());

		System.out.println(Pattern.compile("^[!@#\\$%\\^\\&*\\)\\(+=._-]")
										.matcher("*1stKnight").find());
	}
}

Program output.

true
true
true
true

3. Regex patterns to match end of line

DescriptionMatching Pattern
Line ends with number“\\d$” or “[0-9]$”
Line ends with character“[a-z]$” or “[A-Z]$”
Line ends with character (case-insensitive)[a-zA-Z]$
Line ends with word“word$”
Line ends with special character“[!@#\\$%\\^\\&*\\)\\(+=._-]$”
public class Main {
	public static void main(String[] args) 
	{
		System.out.println(Pattern.compile("[0-9]$").matcher("FirstKnight123").find());

		System.out.println(Pattern.compile("[a-zA-Z]$").matcher("FirstKnight").find());

		System.out.println(Pattern.compile("Knight$").matcher("FirstKnight").find());

		System.out.println(Pattern.compile("[!@#\\$%\\^\\&*\\)\\(+=._-]$")
										.matcher("FirstKnight&").find());
	}
}

Program output.

true
true
true
true

Drop me your questions related to programs for regex starts with and ends with java.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.