简体   繁体   中英

Regex capture groups confusion

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM