0

I've read through the following threads for help on using lookaheads and lookbehinds in regular expressions:

return string with first match Regex

Regex lookahead, lookbehind and atomic groups

Regular expression to match last number in a string

Consider the following string: string = "About 17 or 18 minutes."

At the moment I know how to grab the last numeric (18) using "(\d+)(?!.*\d+)", but I'm having trouble grabbing the first numerical occurrence (17) using a single regular expression instead of re.findall() or re.search() methods.

Here are my attempts. I really hope I'm not too far off...: 1.(?<![0-9])\d+

2.(?<!.*\d+)(\d+) (Invalid...)

I'm testing these on https://pythex.org/ FYI. Any help is very much appreciated, thank you!

EDIT: I've been informed in the comments section that (\d+) can be used and to just isolate the first match. Thank you for the help.

Dascienz
  • 1,071
  • 9
  • 14
  • 3
    `(\d+)` should suffice since a regex engine reads a string from the left to the right. – Casimir et Hippolyte Oct 19 '17 at 19:51
  • 2
    You never have to do anything special to capture the first match, since that's what regular expressions do by default. You only have to jump through hoops to match something later. – Barmar Oct 19 '17 at 19:52
  • @CasimiretHippolyte Thanks, but this will generate 2 matches. Match 1 = 17, Match 2 = 18. I'm trying to understand how to only return a single match, 17. – Dascienz Oct 19 '17 at 19:53
  • 1
    @TreeFiddyBlindMice: choose the good method in this case: `re.search` and not `re.findall` – Casimir et Hippolyte Oct 19 '17 at 19:54
  • @CasimiretHippolyte Okay, I understand what you're saying. I was looking for a shortcut to format some entries. Thank you for the help to you and @Barmar! – Dascienz Oct 19 '17 at 20:02

0 Answers0