如何在python中将字符串转换为正则表达式?

Pan*_*hen 3 python regex string

我从 python 脚本中的命令行参数中获取了一些字符串,并希望将这些字符串用作正则表达式。怎么做?

Inb*_*ose 8

此代码段应该可以帮助您了解要做什么。(Python 2.7.5)

>>> import re
>>> user_string = raw_input('please enter a string to convert to regex: ')
please enter a string to convert to regex: ab(c)
>>> regex = re.compile(user_string)
>>> regex.match('abc').groups()
('c',)
Run Code Online (Sandbox Code Playgroud)

基本上,您可以从中获取输入raw_input,然后将re.compile其转换为正则表达式,然后您可以随意使用它。

注:对于Python 3+只需切换raw_input使用input


Max*_*amy 5

您可以使用 读取命令行参数sys.argv并使用re.compile.

import re
import sys

string_to_convert = sys.argv[1]
regex = re.compile(string_to_convert)
Run Code Online (Sandbox Code Playgroud)