I've been trying to get a regex that matches a string starting with Capital letters [A-Z], optionally including zero or more of these characters(''#', '-', '/' or ' ') and optionally ending with '#' followed by digits:
Example of string: GRAND-CONCOURSE S/T #95
CodePudding user response:
How about this?
r"^[A-Z][-A-Z#/ ]*(?:#\d )?$"
CodePudding user response:
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'
My code might be missing some patterns, so it would be helpful if you provide more examples.