How to define regular expression in java which accepts only those words which starts and end with a
Asked
Active
Viewed 144 times
-1
-
1Something like this should work for you `\b(\w)\w+\1\b` for starts and ends with same letter (your question title). If you mean starts and ends with "a" specifically: `\ba\w+a\b` – CrayonViolent Jan 23 '20 at 18:49
-
yes it is working, can you explain how it is working – Mayur Jan 23 '20 at 18:51
-
Sure! See answer, since it required more info than comment limit – CrayonViolent Jan 23 '20 at 18:55
-
This did not deserve to be closed. The linked answer provides info on how to read a pattern. It does not answer the actual question posted. – CrayonViolent Jan 24 '20 at 22:24
1 Answers
0
Something like this should work for you \b(\w)\w+\1\b
for starts and ends with same letter (your question title).
Explanation:
\b
signifies a word boundary - basically anything \w
would not match.
(\w)
match a single word character and captures it to group 1.
\w+
matches for one or more word characters (to match the rest of the word)
\1
is a back reference to what the capture group 1 matched, to ensure last letter is same as first

CrayonViolent
- 32,111
- 5
- 56
- 79