Andrew Paxson
Andrew Paxson

Reputation: 43

Python Regex: Trying to create pattern

I did my best to check the internet and stack for info but I am having trouble wrapping my head around regex for my utility.

I have a string that follows this pattern:

[any a-z,1-9]_reel[0-9]*2_scn[0-9]*4_shot[0-9]*4

ex:

kim_reel05_scn0101_shot0770

n74_reel05_scn0001_shot0700

ninehundred_reel05_scn0001_shot0700

I need to check those examples to see if it follows that proj_reel##_scn####_shot#### pattern and then if it does proceed! I am not sure how to write this expression as I honestly am having trouble understanding how to use the special characters.

someone want to help me out?

Upvotes: 0

Views: 73

Answers (2)

DevLounge
DevLounge

Reputation: 8437

You can use re.match to test if a string matches your search pattern, if not it returns None.

import re

test = ['kim_reel05_scn0101_shot0770',
        'n74_reel05_scn0001_shot0700',
        'ninehundred_reel05_scn0001_shot0700',
        'proj_reel05_scn0001_shot0700',
        'n74_reel05_scn0001_shot0700',
        'ninehundred_reel05_scn0001_shot0700']


valid = re.compile(r'\bproj_reel[\d]{2}_scn[\d]{4}_shot[\d]{4}\b')

for t in test:
    if re.match(valid, t):
        #proceed
        print('Valid:', t)
    else:
        print('Invalid:', t)

output:

Invalid: kim_reel05_scn0101_shot0770
Invalid: n74_reel05_scn0001_shot0700
Invalid: ninehundred_reel05_scn0001_shot0700
Valid: proj_reel05_scn0001_shot0700
Invalid: n74_reel05_scn0001_shot0700
Invalid: ninehundred_reel05_scn0001_shot0700

Upvotes: 0

vks
vks

Reputation: 67968

^proj_reel[0-9]{2}_scn[0-9]{4}_shot[0-9]{4}$

You can try this.Do not forget to setg and m flags.See demo.

http://regex101.com/r/nA6hN9/35

Upvotes: 2

Related Questions