使用输入创建正则表达式

时间:2018-04-19 14:49:34

标签: regex python-3.x input

编写一个带字符串的函数,并执行与strip()相同的操作 字符串方法。如果没有传递除字符串之外的其他参数 strip,然后将从开头删除空白字符 字符串的结尾。否则,在第二个参数中指定的字符 该函数将从字符串中删除。 (使用正则表达式)

我这样做是为了删除字母或符号的图案,而不是符号类:

import re

def stripas(tekstas, argum):
    tekstas = argum.sub('', tekstas)
    print(tekstas)

print('Input the text:')
tekstas = input()

print('Input the text (Optional):')
argumentas = input()

if argumentas == '':
    argum = re.compile('\s')
else:
    argum = re.compile(argumentas)

stripas(tekstas, argum)

结果使用"" 作为参数(删除了空格):

Input the text:
 hello
Input the text (Optional):

hello
>>> 

结果使用" el" 作为参数(仅删除模式,剩下一个 l ):

Input the text:
 hello
Input the text (Optional):
el
 hlo
>>> 

我的问题最终:是否可以像" [&em> INPUT ]"没有收到错误?

1 个答案:

答案 0 :(得分:0)

你可以试试这个,

if argumentas == '':
    argum = re.compile(r'^\s+|\s+$')       # default: remove leading(or trailing) spaces
else:
    argum = re.compile(r'{}'.format(argumentas))  # for custom removing by input

如果您想要default stripping + custom input removing

argum = re.compile(r'^\s+|\s+$|{}'.format(argumentas))    # default stripping + input characters removing

输出是,

Input the text:
   hello every one
Input the text (Optional):
lo|[en]        # user input regex
   hl vry o    # custom removing by input
hl vry o       # default stripping + custom removing by input
-------------
l+|v.*?e        # lazy mode and quantifier, +,*, etc..
heo ery one
---------------------
(?<=h)e|(?:(?!eve).)+(?= one)   # lookaround
hllo e one