python - String Formatting/Template/Regular Expressions -


i have string format let's = alphanumeric , n = integer template "aaaaaa-nnnn" user ommit dash, , "nnnn" 3 digits in case need pad 0. first digit of "nnnn" has 0, if number is last digit of "aaaaaa" opposed first digit of "nnnn". in essence if have following inputs want following results:

sample inputs:

"sample0001" "sampl1-0002" "sampl3003" "sample-004" 

desired outputs:

"sample-0001" "sampl1-0002" "sampl3-0003" "sample-0004" 

i know how check using regular expressions want opposite. wondering if there easy way other doing nested conditional checking these variations. using python , pandas either suffice.

the regex pattern be:

"[a-za-z0-9][a-za-z0-9][a-za-z0-9][a-za-z0-9][a-za-z0-9][a-za-z0-9]-\d\d\d\d" 

or in abbreviated form:

"[a-za-z0-9]{6}-[\d]{4}" 

it possible through 2 re.sub functions.

>>> import re >>> s = '''sample0001 sampl1-0002 sampl3003 sample-004''' >>> print(re.sub(r'(?m)(?<=-)(?=\d{3}$)', '0', re.sub(r'(?m)(?<=^[a-z\d]{6})(?!-)', '-', s))) sample-0001 sampl1-0002 sampl3-0003 sample-0004 

explanation:

  • re.sub(r'(?m)(?<=^[a-z\d]{6})(?!-)', '-', s) processed @ first. places hyphen after 6th character beginning if following character not hyphen.

  • re.sub(r'(?m)(?<=-)(?=\d{3}$)', '0', re.sub(r'(?m)(?<=^[a-z\d]{6})(?!-)', '-', s)) taking above command's output input, add digit 0 after hyphen , characters following must 3.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -