I'm trying to use regex to check that the first and last characters in a string are alpha characters between a-z.
I know this matches the first character:
/^[a-z]/i
But how do I then check for the last character as well?
This:
/^[a-z][a-z]$/i
does not work. And I suspect there should be something in between the two clauses, but I don't know what!
To match the start or the end of a line, we use the 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.
Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .
They are called “anchors”. The caret ^ matches at the beginning of the text, and the dollar $ – at the end. The pattern ^Mary means: “string start and then Mary”.
In other words, square brackets match exactly one character. (a-z0-9) will match two characters, the first is one of abcdefghijklmnopqrstuvwxyz , the second is one of 0123456789 , just as if the parenthesis weren't there. The () will allow you to read exactly which characters were matched.
The below regex will match the strings that start and end with an alpha character.
/^[a-z].*[a-z]$/igm
The a
string also starts and ends with an alpha character, right? Then you have to use the below regex.
/^[a-z](.*[a-z])?$/igm
DEMO
Explanation:
^ # Represents beginning of a line. [a-z] # Alphabetic character. .* # Any character 0 or more times. [a-z] # Alphabetic character. $ # End of a line. i # Case-insensitive match. g # Global. m # Multiline
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With