Python Regex selecting first option

Viewed 97

I have the following regex that looks for the string 191(x)(y) and (z) and combinations of this (for example - 191(x) , 191(x) and (z).

My regular expression is:

(191?(?:\w|\(.{0,3}\)(?:( (and)?|-)*)){0,5})

See the regex demo.

This expression works for the most part I need help with the following (which I can't figure out):

  • While I do get 5 matches, there are 3 groups, I need to limit the result to only the first group.
  • If I have the text: '191Transit', the regex should only match 191 and ignore the word 'Transit'. in this case it's 'Transit' in other examples this could be any word e.g: 191Bob, 191Smith

I am using Python 3.6.

1 Answers

You can use

191?(?:\([^()]{0,3}\)(?: (?:and)?|-)*){0,5}

See the regex demo

Details

  • Replace .{0,3} to [^()]{0,3} to stay within parentheses
  • Remove one group around ( (?:and)?|-)* as it's redundant
  • Change the groups to non-capturing, i.e. (...) to (?:...)
  • Remove \w alternative, it matches any word char and thus matches 0 to 5 first letters/digits/underscores after 191
Related