0

How to check with Pattern.compile if a string comes after string? For example, I have String: "I love programming a lot!" How can I output only the word programming if and only if there is a word love or like before it? What is the regex for that?

Maximillan
  • 59
  • 3

4 Answers4

1

The simplest method will be to use

.*?(?:love|like).*(programming)

Regex Demo

Using lookaheads

(?=.*?(love|like).*?(programming))

Regex Demo

Java Code

String line = "I love programming a lov lot!"; 
String x = "programming";
String pattern = ".*?(?:love|like).*(" + x + ")";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);

while (m.find()) {
    String tmp = m.group(1);
    System.out.println(tmp);
}

Ideone Demo

rock321987
  • 10,942
  • 1
  • 30
  • 43
1

Don't use Pattern, just use replaceAll():

String lovedThing = str = str.replaceAll(".*(love|like)\\s+(\\S+).*", "$2");

This matches the whole string, replacing it with what's captured in group 2, effectively "extracting" the target, which is matched as "non whitespace chars".

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

This is the essay way to doing this as I think

   String s = "I love programming a lot!";

    if (s.contains("like") || s.contains("love")) {
        System.out.println(s);
    }
Thilina Dharmasena
  • 2,243
  • 2
  • 19
  • 27
0
String s = "I love programming a lot!";
String condition1 = s.indexOf("love");
String condition2 = s.indexOf("like");
String condition3 = s.indexOf("programming");

    if (condition1 < condition3 || condition2 < condition3) {
        System.out.println("programming"); //or get value if not hardcoded
    }
Captain Catz
  • 96
  • 1
  • 12