0

I've need to create regular expression using existing pattern. In my task user enters filename and pattern, my function should return True in case they are compatible and False if not.

For example, if filename='log1.txt', and pattern='log?.txt' it should return True.

So I tried to use new variable and replace method (PT = pattern.replace('?', '\w')) to collect needed RE and return bool(re.fullmatch(pt, filename)) after that, but replace method gives me '\\w' instead '\w'. I tried several ways but no luck.

Ev An
  • 1
  • 1

1 Answers1

0

it shows double \\ because your replace value having a symbol \ so when you call the PT object that shows double \\ one for your input one for indicating symbol if you don't want to see double \\ then simply use print command that can print only single \ which you want to include.

pattern='log?.txt'


PT = pattern.replace('?', '\w')

print(PT)

log\w.txt

If you want to match filename and pattern. Try this.

import re      

filename='log1.txt'
pattern='log?.txt'

def unix_match(filename: str, pattern: str) -> bool:
      pt = re.sub('\[.*\] ', '', pattern)      
      filename = re.sub('[1-9]', '', filename)
  
      return bool(re.fullmatch(pt, filename))
  
unix_match(filename,pattern)
Sahil Desai
  • 3,418
  • 4
  • 20
  • 41