在下面的代码块中,我想使用python正则表达式忽略'@'和“everything”以获得输出“match upto” 我可以帮助我吗?
import re
mytext = "@ match everything upto"
myex = re.compile(r"") # Here I want to put regular expression
matches = re.findall(myex, mytext)
print (matches)
for i in matches:
print(i)
print (len(matches))
答案 0 :(得分:2)
这就是您要找的re.sub
import re
mytext = "@ match everything upto"
myex = re.compile(r"(@|everything)")
final_str = re.sub(myex, '',mytext)
print(final_str)
输出:
match upto
说明:
re.compile(r"(@|everything)")
以上re
仅表示@
或everything
。 re.sub()
有三个参数re.sub(pattern,replacement_string,string_to_be_searched)
所以在你的情况下:re.sub(myex, '',mytext)
其中替换字符串是一个空字符串''
答案 1 :(得分:0)
您可以使用list comprehensions
mytext = "@ match everything upto"
r_items=['@','everything']
mytext = [x for x in mytext.split() if x not in r_items]
print(' '.join(mytext))
输出:
match upto