runsun
runsun

Reputation: 462

Python3: Enter regex pattern from command line

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) )

Upvotes: 1

Views: 3758

Answers (2)

runsun
runsun

Reputation: 462

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 [ ].

Upvotes: 1

Jan
Jan

Reputation: 43169

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

Upvotes: 0

Related Questions