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

Time:02-18

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:

[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?

CodePudding user response:

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

CodePudding user response:

You may use String#matches() here with a backreference:

List<String> inputs = Arrays.asList(new String[] {"Apple for Apple", "Apple for Orange"});
for (String input : inputs) {
    if (input.matches("(\\w ) for \\1")) {
        System.out.println("MATCH   : "   input);
    }
    else {
        System.out.println("NO MATCH: "   input);
    }
}

This prints:

MATCH   : Apple for Apple
NO MATCH: Apple for Orange
  • Related