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?
Asked
Active
Viewed 92 times
0

Maximillan
- 59
- 3
4 Answers
1
The simplest method will be to use
.*?(?:love|like).*(programming)
Using lookaheads
(?=.*?(love|like).*?(programming))
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);
}

rock321987
- 10,942
- 1
- 30
- 43
-
What if I have an arbitrary word after `like` and `love`. Is there any way for that ? @rock321987 – Maximillan May 02 '16 at 03:14
-
@Maximillan it will work for any word..try it..can you specify the case? – rock321987 May 02 '16 at 03:15
-
@Maximillan you need to know that word beforehand..how will you be able to determine which word to match after `love` or `like`? – rock321987 May 02 '16 at 03:16
-
@Maximillan If you know the word beforehand(or it is user input), you can concatenate it with regex.. – rock321987 May 02 '16 at 03:20
-
thats exactly what i want! but how to concatenate? For example, given `I love x` it should print only `x` where `x` can be any word. – Maximillan May 02 '16 at 03:25
-
@Maximillan `String regex = ".*(love|like).*(" + x + ")"` ..you can compile this regex and find the results – rock321987 May 02 '16 at 03:40
-
@Maximillan see **[this](http://ideone.com/esKyZk)** on ideone – rock321987 May 02 '16 at 03:46
-
@Maximillan consider accepting the answer if ti helped – rock321987 May 02 '16 at 05:31
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
-
For example, given I love x it should print only x where x can be any word. @Bohemian – Maximillan May 02 '16 at 03:27
-
-
-
@max group 2 from the match. A group is formed using brackets. Groups are numbered starting from 1 – Bohemian May 02 '16 at 07:26
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