Python字符串(参数) - >正则表达式

时间:2013-02-16 06:21:56

标签: python regex arguments

我正在尝试将一个正则表达式作为我的python程序的参数(这自然是一个字符串)并简单地将它与另一个字符串匹配。

假设我将其作为

运行

python program.py 'Hi.there'

我希望能够接受输入(称之为输入)并说明它是否与'HiTthere'相匹配(它应该)。

我该怎么做?我对正则表达式缺乏经验。

2 个答案:

答案 0 :(得分:2)

Python 3语法(Python 2,使用print xxx而不是print(xxx)):

import re

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

请注意,我正在使用锚点^$来保证匹配跨越整个输入。 ^匹配字符串的开头,$匹配字符串的结尾。

有关详细信息,请参阅the documentation

答案 1 :(得分:2)

根据我的理解,你正在寻找类似的东西:

import sys, re

regex = sys.argv[1]

someOtherString = 'hi there'

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

使用表达式作为第一个参数运行此程序:

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

与javascript不同,python正则表达式是简单的字符串,因此您可以直接使用sys.argv[1]作为re.search的参数。