I am struck in writing regular expression for below format XXXXXXG0-XXXX-XXXX-1923-785FEABCD128 Above format is to filter MAC Address, so i need those MAC ADDRESS which has the characters defined in the above format and length
Is it possible to write regexp for above format? X characters can be alphanumeric. But other non X characters should be same.
ABCDEFG0-GHYD-SDER-1923-785FEABCD128 - Valid
ABCDEFH0-GHYD-SDER-0923-995FEABCD120 - Invalid
ABCDEFG0-GHYD-SDER-0923-995FEABCD120 - Invalid
^[a-zA-Z0-9]{6}G0-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-1923-785FEABCD128$
Explanation:
^ matches beginning of the string
[a-zA-Z0-9]{6} matches any alphanumeric character 6 times
G0- matches that text exactly
[a-zA-Z0-9]{4}- any alphanumeric character 4 times followed by a hyphen (appears twice)
1923-785FEABCD128 matches that text exactly
$ matches the end of the string
import re
patt = re.compile('[A-Z0-9]{6}G0-[A-Z0-9]{4}-[A-Z0-9]{4}-1923-785FEABCD128')
for test in ['ABCDEFG0-GHYD-SDER-1923-785FEABCD128', 'ABCDEFH0-GHYD-SDER-0923-995FEABCD120', 'ABCDEFG0-GHYD-SDER-0923-995FEABCD120']:
if patt.match(test):
print(f'{test} - Valid')
else:
print(f'{test} - Invalid')
prints
ABCDEFG0-GHYD-SDER-1923-785FEABCD128 - Valid
ABCDEFH0-GHYD-SDER-0923-995FEABCD120 - Invalid
ABCDEFG0-GHYD-SDER-0923-995FEABCD120 - Invalid
For the sake of string-matching instead of a regex, you could use this solution:
mac_addresses = [
'ABCDEFG0-GHYD-SDER-1923-785FEABCD128',
'ABCDEFH0-GHYD-SDER-0923-995FEABCD120',
'ABCDEFG0-GHYD-SDER-0923-995FEABCD120'
]
for address in mac_addresses:
# splits 3 times, leaving the last two groups together
# for easier string matching
first, *_, last = address.split('-', 3)
if first.endswith('G0') and last == '1923-785FEABCD128':
match = 'Valid'
else:
match = 'Invalid'
print(f"{address} - {match}")
Which prints
ABCDEFG0-GHYD-SDER-1923-785FEABCD128 - Valid
ABCDEFH0-GHYD-SDER-0923-995FEABCD120 - Invalid
ABCDEFG0-GHYD-SDER-0923-995FEABCD120 - Invalid
The benefit here? If you need to change conditions or add a new condition, you don't need to modify/keep up with a regex