2

I have a Python script which accepts a regex pattern, and it does something like this:

import sys
import re

pattern = re.compile(sys.argv[1])
time_string = '2017-08-14 11:07:46'

def func(pattern):
    if re.search(pattern, time_string):
        # do something

But when I run python script.py \d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2}:\d{2} the condition in the function always ends up false. I'm stuck with this problem for days and I need help. Thanks in advance.

0

1 Answer 1

4

You forgot to escape the '\' characters, they are special to bash:

python script.py \\d{4}\-\\d{2}\-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}

Or as comment suggests, put the whole string in single quote, then '\' will be treated literally:

python script.py '\d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2}:\d{2}'
Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively, just python script.py '\d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2}:\d{2}'.
@SergiyKolesnikov Good point, updated.