Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match first and last character

Tags:

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!

like image 753
Jason Avatar asked Jun 21 '14 11:06

Jason


People also ask

How do I specify start and end in regex?

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.

How do I match a character in regex?

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 "@" .

What matches the start and end of the string?

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”.

What is difference [] and () in regex?

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.


1 Answers

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 
like image 99
Avinash Raj Avatar answered Sep 20 '22 15:09

Avinash Raj