Reputation: 561
How do I grab the first word after my match?
For example, once I find Car
, how do I grab Chevy
?
public class NewExtractDemo {
public static void main(String[] args) {
String input = "I have the following Car: Chevy, Truck: Ford, Van: Honda";
Pattern p = Pattern.compile("(Car|Truck|Van)");
Matcher m = p.matcher(input);
List<String> Search = new ArrayList<String>();
while (m.find()) {
System.out.println("Found a " + m.group() + ".");
Search.add(m.group());
}
}
}
Upvotes: 3
Views: 7214
Reputation: 42010
Consider using a constant to avoid recompiling the regular expression each time.
/* The regex pattern that you need: (?<=(Car|Truck|Van): )(\w+) */
private static final REGEX_PATTERN =
Pattern.compile("(?<=(Car|Truck|Van): )(\\w+)");
public static void main(String[] args) {
String input = "I have the following Car: Chevy, Truck: Ford, Van: Honda";
Matcher matcher = REGEX_PATTERN.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
Output:
Chevy
Ford
Honda
Upvotes: 0
Reputation: 129497
Use capturing groups:
(Car|Truck|Van):\s*(\w+)
Now .group(1)
will return Car
and .group(2)
will return Chevy
.
String input = "I have the following Car: Chevy, Truck: Ford, Van: Honda";
Pattern p = Pattern.compile("(Car|Truck|Van):\\s*(\\w+)");
Matcher m = p.matcher(input);
while (m.find()) {
System.out.println(m.group(1) + "\t" + m.group(2));
}
Car Chevy Truck Ford Van Honda
Upvotes: 16