Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

Regex pattern starting with capital letters and ending in optional '#'followed by digits python ?

By M.K. Verma · 3 May 2022

Regex pattern starting with capital letters and ending in optional '#'followed by digits python ?

I provided a code with sample examples. I used re to check if the input is matched with a pattern or not, as follows:

import re

examples = [
    'GRAND-CONCOURSE S/T #95',
    'GRAND-CONCOURSE S/T',
    'GrandCONCOURSES/T',
    'GrandCONCOURSES/T#95',
    'G',
    'g',
    'grand-CONCOURSE S/T #95',
    'grand-CONCOURSE S/T',
]

# starts with capital letter(s) and several characters can be located after the capital letter(s) (or not).
p = re.compile('^[A-Z]+[0-9#/ -]*')
for example in examples:
    matched = p.match(example)
    if matched:
        print(True, example)
    else:
        print(False, example)
# RESULT
True 'GRAND-CONCOURSE S/T #95'
True 'GRAND-CONCOURSE S/T'
True 'GrandCONCOURSES/T'
True 'GrandCONCOURSES/T#95'
True 'G'
False 'g'
False 'grand-CONCOURSE S/T #95'
False 'grand-CONCOURSE S/T'