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
Description | Matching 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
Description | Matching 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?
Let us know if you liked the post. That’s the only way we can improve.