python-3.xregexicd

Python: ICD-10 RegEx


Goal: create regex of ICD-10 codes.

Format

I've most of the 1st half:

r'[A-Z][0-9][0-9]'

The second half I'm stuck on:

([a-z]|[0-9]){1,4}$

If there is something generated, it must have a dot .

Examples: .0 or .A9 or .A9A9 or .ZZZZ or .9999 etc.


Test Python RegEx

Note: I know some ICD-10 codes don't surpass a certain number/ letter; but I am fine with this.


Solution

  • You can use

    ^[A-Z][0-9][A-Z0-9](?:\.[A-Z0-9]{1,4})?$
    

    See the regex demo. Details:

    In Python code, you can use the following to validate string input:

    icd10_rx = re.compile(r'[A-Z][0-9][A-Z0-9](?:\.[A-Z0-9]{1,4})?')
    if icd10_rx.fullmatch(text):
        print(f'{text} is valid!')
    

    Note the anchors are left out because Pattern.fullmatch (same as re.fullmatch) requires a full string match.