1

I'm trying to create a Python regular expression that will match a string if and only if that string begins and ends with the same lower-case letter. The following seems like it ought to work, but matches every string:

(?P<st>[a-z]).*(?P=st)$

Any suggestions will be appreciated.

0

2 Answers 2

3
^([a-z]).*\1$

This will require back reference.See demo.

https://regex101.com/r/iV6mP5/5#python

import re
p = re.compile(r'^([a-z]).*\1$', re.MULTILINE)
test_str = "a sdf sd fdsf sd a\nsdfdsf ASDSDSAD@#$@#ASDASDs\nsadasd Wdsda"

re.findall(p, test_str)
Sign up to request clarification or add additional context in comments.

Comments

0

I realize you asked for a regex, but then again, so many people ask that because they somehow think that's the only way to do these things.

>>> for s in ('test', 'foo', 'Test', ''):
    if s and s[0].islower() and s[0] == s[-1]:
        print('good:', s)

good: test

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.