简体   繁体   中英

Regex, split at groups and get numbers

https://regexr.com/5u8j6

Expression: (?<=\/)(\d*)

/v1/vehicles/A123
/v1/vehicles/123
/v1/vehicles/123/456
/v1/vehicles/999fd7d6-1b79-4471-9954-3d63deabaa31

Must match with:

123
123,456

But I am getting 999 too

My two cents to solving your problem:

\/(\d+)(?=$|\/)

See an online demo

  • \/ - A literal forward slahs.
  • (\d+) - A capture group to match 1+ digits ranging 0-9.
  • (?=$|\/) - Positive lookahead to match end-string anchor or a literal forward slash.

Other options could be:

(?<=\/)\d+(?=$|\/)

Or:

\/\K\d+(?=$|\/)

This will help, too:

(?<=\/)([0-9]+)(?![^\/])

See this proof (only test one string by one).

EXPLANATION

--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    \/                       '/'
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [0-9]+                   any character of: '0' to '9' (1 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    [^\/]                    any character except: '\/'
--------------------------------------------------------------------------------
  )                        end of look-ahead

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