Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a string that starts and ends with the same letter?

Tags:

regex

How do I write a regular expression that consists of the characters {x,y} but must start and end with the same letter? For example:

  • xyyyxyx
  • yxyxyxy
like image 252
Mat.S Avatar asked Mar 18 '14 22:03

Mat.S


People also ask

What matches the start and end of the string?

The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”. The caret ^ matches at the beginning of the text, and the dollar $ – at the end.

How do you match a string to a pattern?

Put brackets ( [ ] ) in the pattern string, and inside the brackets put the lowest and highest characters in the range, separated by a hyphen ( – ). Any single character within the range makes a successful match.

How do you match the end of a string?

End of String or Before Ending Newline: \Z The \Z anchor specifies that a match must occur at the end of the input string, or before \n at the end of the input string.

Which character is used to match end of a string?

The ^ and $ match the beginning and ending of the input string, respectively. The \s (lowercase s ) matches a whitespace (blank, tab \t , and newline \r or \n ). On the other hand, the \S+ (uppercase S ) matches anything that is NOT matched by \s , i.e., non-whitespace.


2 Answers

This should work for you:

^(x|y).*\1$

This regex will match a string that starts and ends with the same letter (as the post title suggests), but does not limit the string to contain only x and y characters. It will match any strings, starting and ending with the same letters specified in the parenthesis.

It will match strings consisting of {x,y} characters, starting and ending with the same letter: (as the OP specified.)

xyyyxyx
yxyxyxy
zxyxyxz
xyxyxyy

But it will also match strings with any characters in between (not limited to only x and y):

xgjyhdtfx
yjsaudgty
xuhgrey
yudgfsx
yaaay

Working regex example:

https://regex101.com/r/TER7zI/1

like image 82
Bryan Elliott Avatar answered Nov 15 '22 06:11

Bryan Elliott


This regex works:

^([xy])[xy]*\1$|^[xy]$

I tested it on regexr with

xyyyxyx
yxyxyxy
x
y
xyyyxyy
yxyxyxx
xyzyxx
z

and it only matched the first four.

like image 35
The Guy with The Hat Avatar answered Nov 15 '22 08:11

The Guy with The Hat