Regex - Stop after finding the first pattern

Viewed 71

For a string like this:

1. Jane, Doe2. Good, Jay3. Turn, Bob[key]

Either Jane, Doe needs to be extracted if no [key] is present then whatever is between 1. and 2. (or)

Turn, Bob if [key] is present

Put another way:

  1. If [key] is present, then the person before [key] needs to be extracted and the process stopped.
  2. If [key] is not present, then pick up whoever is after 1.

I tried this but it pulls up both Jane, Doe and Turn, Bob

(\.([^\.])(.+)\[key\])|(1\.(.+)2\.)

How to stop after finding the first successful pattern, knowing that patterns are read left to right? [key] can be anyone - 1,2 or 3.

Thanks.

2 Answers

For these requirements, you may use this regex in Python with an alternation:

(?<=\d\.\s)[a-zA-Z, ]+(?=\[key])|(?<=1\.\s)(?!.*\[key])[a-zA-Z, ]+

RegEx Demo

RegEx Details:

  • (?<=\d\.\s): Positive lookbehind to assert that there is a digit followed by dot followed by a whitespace before the current position
  • [a-zA-Z, ]+: Match 1+ of letter, space or comma characters
  • (?=\[key]): Positive lookahead to assert that there is a text [key] after the current position
  • |: OR
  • (?<=1\.\s): Positive lookbehind to assert that there is a digit 1 followed by dot followed by a whitespace before the current position
  • (?!.*\[key]): Negative lookbehind to assert that there is no [key] text after the current position
  • [a-zA-Z, ]+: Match 1+ of letter, space or comma characters

Not sure why you put .+ into your regex but it's greedy and matches . Good, Jay3. Turn, Bob. so the left part of the alternation matches.

Suggest you remove the .+ on both sides of the alternation ( | ).

Related