Python regex to match 6-digit numbers of different formats

Viewed 384

I need to find and capture all occurrences of 6 digit numbers with OMIM and MIM prefixes and all 6 digit numbers where there is no preceding colon.

Expected output

[111111, 222222, 555555, 444444]

What I have tried

import re

sentence = '111111;Dystonia-1,222222,OMIM:555555; 3333333 Dystonic disorder1,MIM#444444'

re1 = r'OMIM:(\d{6})'
re2 = r'MIM#(\d{6})'
re3 = r'[^:](\d{6})'

identifiers = re.compile("(%s|%s|%s)" % (re1, re2, re3)).findall(sentence)

Current output

[
  ( ',222222'     , ''       , ''       , '222222' ),
  ( 'OMIM:555555' , '555555' , ''       , ''       ),
  ( ' 333333'     , ''       , ''       , '333333' ),
  ( 'MIM#444444'  , ''       , '444444' , ''       )
]
1 Answers

I think you could try:

\b(?:MIM#|OMIM:|(?<!:))(\d{6})\b

See the online demo

  • \b - Word boundary.
  • (?: - Non-capture group:
    • MIM#|OMIM:|(?<!:) - Literally "MIM#" or "OMIM:" or a negative lookbehind to assert position is not preceded by a colon.
    • ). Close non-capture group.
  • (\d{6}) - Capture six digits in a capture group.
  • \b - Word boundary.

import re
sentence = '111111;Dystonia-1,222222,OMIM:555555; 3333333 Dystonic disorder1,MIM#444444'
print(re.findall(r'\b(?:MIM#|OMIM:|(?<!:))(\d{6})\b', sentence))

Prints:

['111111', '222222', '555555', '444444']
Related