1

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.

2 Answers 2

3

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.

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

1 Comment

Okay, cool. This helps (I didn't know that regexes are just strings). Just a quick note, I was looking for the number of times that was found (so instead of search, I'm now using findall)
2

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.

7 Comments

Although, you really only need the $ anchor since re.match starts at the start of the string by default.
Yep. I find using ^/$ as a pair to be more explicit, but you can skip ^.
This is helpful, but the thing is that I have the 'Hi.there' as a string object first (as I pass it as an argument to the program, not as a string literal). Can I do the same thing?
@RiverTam -- Sure. Just substitute 'HiTthere' with sys.argv[1] (with proper import of course).
Are you looking for a pattern in another string? My answer was for matching an entire string with a pattern. To search, use re.search and leave off the anchors (^/$).
|

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.