- Unlike character set, anchors in Regex are used to match positions before, after and in between
- They are used to “Anchor” the regex match at a certain position.
- The caret “^” matches the position before first character in a single line
Example : In text “abc” regex “^a” matches the letter “a” - The dollar “$” matches the position after last character in a single line
Example : In text “xyz” regex “z$” matches the letter “z” - Note : Anchors matches/searches line by line and not word by word hence they are great to validate single word input from users in applications like email id or number only input.
- Searching caret “^” and dollar “$” in a multi-line text (Note : CR LF is \n in windows)
- Example 2:
Input : Text should contain number inputs only “746746746”
Regex : ^\d+$ - Example 3:
Input : Find the starting and ending spaces in paragraph
Regex : ^\s+|\s+$
Permanent Start and End of String
- As discussed above “^” and “$” works line by line and with multiple lines together, suppose in a scenario you want to find what is the start of a String in multiple lines in a file the you can go for “\A” and “\Z” instead.
- \A check the first position of the first line in multiple lines.(Example Below)
- \Z checks of the last position of the last line in multiple lines.(Example Below)
Note : If you want to match the line break “\n” position as well then you can use “\z” which will return you the position after \n