Regular expression to match first and last character
Asked Answered
L

5

31

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!

Laurasia answered 21/6, 2014 at 11:5 Comment(0)
G
62

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
Gilroy answered 21/6, 2014 at 11:8 Comment(9)
Lookahead is completely unnecessary here.Hinz
This is completely identical to the other answer.Geographical
he misses the g modifier.Gilroy
Why do you need g modifier?Solidstate
@M42 g modifier: global. All matches (don't return on first match)Gilroy
Sure, but it has nothing to do here because we match the whole string.Solidstate
without g modifier, it fails to match the string in the second line.regex101.com/r/jO2pI2Gilroy
Kudos to you for explaining that sh**! :)Lali
@AvinashRaj, what should I do to make the first character== last character in your regex.Crotch
W
11

You can do it as follows to check for the first and last characters and then anything in between:

/^[a-z].*[a-z]$/im

DEMO

Wobbly answered 21/6, 2014 at 11:6 Comment(4)
The flag m would help as well.Gerstner
@hjpotter92, Thank you. I have included it in my answerWobbly
@Wobbly .* would have done instead of .*?. Backtracking will be better because of anchor.Geographical
@Unihedron, Thank you. I have changed my answer. I guess I just feel safer with .*?Wobbly
N
2

You can use this:

/^.|.$/gim

it matches with first and last character

Neile answered 14/7, 2022 at 14:45 Comment(0)
J
1
 var str = "Regular";
//following code should return true as first and last characters are same
var re = /(^[a-zA-Z])(.*)\1$/gi;

console.log(re.test(str); //true

Match 1 : Regular
Group 1 : (^[a-zA-Z]) = R
Group 2 : (.*) = egula
\1$ : Match the same what is caught in group 1 at the end = r
Jinnyjinrikisha answered 18/12, 2021 at 10:3 Comment(1)
That is not was asked.Solidstate
W
0

put characters in groups like ([group1])([group2])\1. The \1 says the last group matches group 1.

([a-z])([someRegex])\1
Westerly answered 4/10, 2022 at 16:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.