英文:
Replace string with other with two possible patterns in python
问题
I would like to replace everything in String untill "err" or "error" appear for empty string.
So:
"abc err efg" -> "efg",
"abc error efg" -> "efg.
How to do it with one pattern using re.sub?
I tried this:
lines_input = ['some line err hello', 'some line error hello']
rep = {'^.*?err': '', '^.*?error': ''}
dict((re.escape(k), v) for k, v in rep.items())
pattern = re.compile("|".join(rep.keys()))
for line in lines_input:
print pattern.sub(lambda m: rep[re.escape(m.group(0))], line)
and had KeyError. Would like to have:
hello
hello
英文:
I would like to replace everything in String untill "err" or "error" appear for empty string.
So:
"abc err efg" -> "efg",
"abc error efg" -> "efg.
How to do it with one pattern using re.sub?
I tried this:
lines_input = ['some line err hello', 'some line error hello']
rep = {r'^.*?err': '', r'^.*?error': ''}
dict((re.escape(k), v) for k, v in rep.items())
pattern = re.compile("|".join(rep.keys()))
for line in lines_input:
print pattern.sub(lambda m: rep[re.escape(m.group(0))], line)
and had KeyError. Would like to have:
hello
hello
答案1
得分: 5
不需要多个正则表达式。这两个模式除了error
末尾的可选or
不同外,都相同,因此使用可选组。
line = re.sub(r'.*err(or)?\s*', '', line)
英文:
You don't need multiple regular expressions. The two patterns are the same except for the optional or
at the end of error
, so use an optional group.
line = re.sub(r'.*err(or)?\s*', '', line)
答案2
得分: 3
使用您提供的示例,请尝试以下Python代码。此代码已在Python 3.10中编写和测试,它使用了re
库和正则表达式( err(?:or)?(?: |$))
的split
函数。
另外,如果列表的元素不包含error
或err
,则不会打印任何内容。
##导入Python的re库。
import re
##输入:
lines_input = ['some line err hello', 'some line error hello', 'hi there!!!']
##Python代码:
[val2[-1] for val2 in [re.split('( err(?:or)?(?: |$))', val1) for val1 in lines_input] if len(val2) >= 2]
英文:
With your shown samples please try following Python code. Written and tested in Python3.10. Its using re
library and split
function using regex ( err(?:or)?(?: |$))
.
Also if an element of list is not having error
OR err
then it will not print anything in it.
##Importing re library of Python here.
import re
##Input:
lines_input = ['some line err hello', 'some line error hello', 'hi there!!!']
##python:
[val2[-1] for val2 in [re.split('( err(?:or)?(?: |$))',val1) for val1 in lines_input] if len(val2)>=2]
答案3
得分: 1
你可以使用单一的模式来实现这一点
import re
lines_input = ['some line err hello', 'some line error hello']
pattern = re.compile(r'^.*?\b(?:err|error)\b')
for line in lines_input:
# 用空字符串替换匹配的部分
modified_line = pattern.sub('', line)
print(modified_line.strip())
输出
hello
hello
英文:
You can achieve that with a single pattern
import re
lines_input = ['some line err hello', 'some line error hello']
pattern = re.compile(r'^.*?\b(?:err|error)\b')
for line in lines_input:
# Replace the matched portion with an empty string
modified_line = pattern.sub('', line)
print(modified_line.strip())
Output
hello
hello
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论