Reputation: 3686
I have the following text
Jul 31, 2015 - Departure 2 stops Total travel time:20 h 40 m
Aug 26, 2015 - Return 1 stop Total travel time:19 h 0 m Chicago
nonstop
I want to get the digit that precedes text that looks like "stop(s)" and all instances of "nonstop", however I want both to be in the same capture group.
I wrote this regex
(\d)(?:\Wstops?)|(nonstop)
This does what I want but as you see it consists of two capture groups (group #1 for the digits and group #2 for 'nonstop'), can this be done with a single capture group?
My other question, is it possible to directly return 'nonstop' as 0 using regex, instead of processing the text in code later on?
Here is a live demo of my regex: regex101
Upvotes: 3
Views: 100
Reputation: 174696
You need to use positive lookahead assertion.
Matcher m = Pattern.compile("\\d(?=\Wstops?)|nonstop").matcher(s);
while(m.find())
{
System.out.println(m.group());
}
\\d(?=\Wstops?)
matches all the digits only if it's followed by a non-word character again followed by the string stop
or stops
|
OR
nonstop
match the string nonstop
Upvotes: 4