Bhimasen
Bhimasen

Reputation: 757

how to give priority for a regex pattern over another

I am using regular expressions to extract university names. Mainly two patterns are observed.

  1. "some name" university --> ex: Anna University
  2. university of "something" --> ex: University of Exeter

For this, I have written two patterns as,

regex = re.compile('|'.join([r'[Uu]niversity of (\w+){1,3}',r'(?:\S+\s){1,3}\S*[uU]niversity']))

But in few cases I am not getting proper expected answer. For example,

sentence  = "Biology Department University of Vienna"

For this sentence, applying above regular expression, I am getting

"Biology Department University"

which is wrong. I feel, since both patterns will be matched, the second pattern is getting matched and phrase is extracted.

I need to give priority for first pattern, so that "university of something" will be extracted in similar scenario.

can anybody help

Upvotes: 11

Views: 16633

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336168

In general, alternations in regular expressions are evaluated from left to right, so the leftmost alternatives are checked first, giving them priority. You already did that, though - the reason why you still got the match from the right side of the alternation is that that match is possible earlier in the string.

Therefore you need to be more specific and only allow a "Foo University" match only if no of follows. You can use a negative lookahead assertion for this:

regex = re.compile('|'.join([r'university of (\w+){1,3}',
                             r'(?:\S+\s){1,3}\S*university(?!\s+of\b)']),
                   flags=re.I)

Upvotes: 20

Related Questions