Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java: Regex to match when a string is present twice before and after a known string

I am looking for a java regular expression to match random string like this:

Apple for Apple
day for day
Money for Money
... etc.

So the regular expression should match the string if there is a "for" and an identical word before and after.

Currently i’m using this regex:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[A-Za-z]+[ ]{1}(for){1}[ ]{1}[A-Za-z]+

But it also returns wrong results like:

Apple for all
day for night
... etc.

I’d like to accomplish this with Regex only and no extra Java code. Is this possible?

>Solution :

You can use groups to match the words before and after ‘for’.

Try this: ^(\\w+) for \\1
Yes those are spaces between for, you can use ‘\s’ too but then it will match all white space chars like \n, \r, \t etc.

Explanation:

^(\\w+) for \\1

^      beginning of the string
(\\w+)  capture group to catch any word
       matches white space
for    matches 'for'
       matches white space
\\1     matches the word captured in the first capture group

Test the regex here: https://www.regexplanet.com/share/index.html?share=yyyyp3haukr

and here: https://regex101.com/r/wJvwob/1

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading