Regex 使用输入创建正则表达式
编写一个接受字符串并执行与strip()相同操作的函数 字符串方法。如果除了字符串之外没有其他参数传递给 strip,则将从开头和结尾处删除空白字符 绳子的末端。否则,第二个参数中指定的字符 将从字符串中删除函数的。(使用正则表达式) 我这样做是为了去除字母或符号的图案,而不是符号的类别:Regex 使用输入创建正则表达式,regex,python-3.x,input,Regex,Python 3.x,Input,编写一个接受字符串并执行与strip()相同操作的函数 字符串方法。如果除了字符串之外没有其他参数传递给 strip,则将从开头和结尾处删除空白字符 绳子的末端。否则,第二个参数中指定的字符 将从字符串中删除函数的。(使用正则表达式) 我这样做是为了去除字母或符号的图案,而不是符号的类别: import re def stripas(tekstas, argum): tekstas = argum.sub('', tekstas) print(tekstas) print('
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)
使用“”作为参数的结果(已删除空格):
使用“el”作为参数的结果(仅删除模式,保留一个l):
最后,我的问题是:是否可以像“r'[INPUT]”一样创建类而不出错?您可以试试这个
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
如果要默认剥离
+自定义输入删除
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
输入文本:
大家好
输入文本(可选):
lo |[en]#用户输入正则表达式
hl vry o#通过输入自定义删除
hl vry o#默认剥离+输入自定义移除
-------------
l+| v.*e#惰性模式和量词,+,*,等等。。
好的
---------------------
(?我只是暂停了这一步。嗯,有趣的是,带空格的第一部分按你的方式删除了它的逻辑,因为按我的方式运行程序会使用^和$works删除所有空格,即使在单词之间也是如此。然而,即使我只输入:else:argum=re.compile(argumentas)并只输入表达式,第二次更改的效果也是一样的。{}.format我还不熟悉这个语法:)我想知道如何将stuff int放在(r'stuff')之间。非常感谢。怎么了?有什么问题吗?如果输入字符串有多行,那么使用多行标志
,(?m)
,然后上面的空白去除正则表达式将更改为r'(?m)^\s+\s+$”
,如果我有多行文本,我可以添加一个参数。可以添加许多参数,如re.DOTALL。示例:someRegexValue=re.compile('foo',re.IGNORECASE | re.DOTALL | re.VERBOSE)好的,就是这样:-)
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