River Tam
River Tam

Reputation: 3216

Python string (argument) -> Regex

I'm trying to take a regular expression as an argument to my python program (which is a string naturally) and simply match it against another string.

Let's say I run it as

python program.py 'Hi.there'

I'd like to be able to then take that input (call it input) and say whether or not it matches 'HiTthere' (it should).

How should I do this? I'm inexperienced at regex.

Upvotes: 1

Views: 4964

Answers (2)

georg
georg

Reputation: 214969

From my understanding, you're looking for something like:

import sys, re

regex = sys.argv[1]

someOtherString = 'hi there'

found = re.search(regex, someOtherString)
print('ok' if found else 'nope')

Run this program with an expression as a first argument:

> python test.py hi.th
ok
> python test.py blah
nope

Unlike, say, javascript, python regexes are simple strings, so you can directly use sys.argv[1] as an argument to re.search.

Upvotes: 3

nneonneo
nneonneo

Reputation: 179422

Python 3 syntax (Python 2, use print xxx instead of print(xxx)):

import re

if re.match(r'^Hi.there$', 'HiTthere'): # returns a "match" object or None
    print("matches")
else:
    print("no match")

Note that I'm using the anchors ^ and $ to guarantee that the match spans the entire input. ^ matches the start of the string and $ matches the end of the string.

See the documentation for much more detail.

Upvotes: 2

Related Questions