1

I have a script searching for, say, a word + "(". I'd use:

pattern = re.compile( "anyword\(" )

But I want to have users enter the pattern string from the command line (Windows 10).

argp = argparse.ArgumentParser()
argp.add_argument("-p", metavar="pattern", type=str,
                 , help="regex pattern")
args= argp.parse_args()
pattern = re.compile( args.p )

But it fails to handle anyword\( properly. Is there anyway to do this?

I've tried the following but none got it to re.compile(anyword\():

pattern = re.compile( bytes( args.p, "utf-8").decode('unicode_escape') ) 
pattern = re.compile( str.encode( args.p ).decode('unicode_escape') )
pattern = re.compile( eval( args.p) )
2
  • can you share input string as well ? Commented Nov 4, 2017 at 6:11
  • 2
    The user may need to escape the backslash when entering it on the command line. Commented Nov 4, 2017 at 6:36

2 Answers 2

1

I've got two good approaches from responses to a google page:

Dhruv Kanojia(Xonshiz) wrote a regexEntry.py that uses this:

pattern = re.compile("{0}".format(user_input))

and Evgeniy Lobov simply uses:

pattern = re.compile("anyword[(]")

Both work but Dhruv's approach doesn't require users to add [ ].

Sign up to request clarification or add additional context in comments.

Comments

0

I'd reckon that this is is a rather bad approach (escaping on the command line, etc.), but this works:

import argparse, re

ap = argparse.ArgumentParser()
ap.add_argument("-p", "--pattern", required = True, help= "regex pattern")
args = vars(ap.parse_args())

string = "here is someword hidden"

if re.search(args["pattern"], string):
    print("Found")

When calling via python task.py -p "someword.+" this yields

Found

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.