提问人:sandeep 提问时间:10/21/2023 最后编辑:sandeep 更新时间:10/25/2023 访问量:98
查找并删除/替换较大字符串的一部分
Find and delete/replace a part of bigger string
问:
在我的 python/Django 项目中,我正在尝试编写一个自定义异常类,我想避免向最终用户显示很少的东西。
在下面的错误消息中,如果您看到项目名称正在显示。我想在消息进入 UI 之前将其删除。prj-eng-d-nc-prcd-1077
我试图找到并替换。例如:
prj_name = 'prj-eng'
if prj_name in msg:
msg = msg.replace(prj_name, '')
print (msg)
但这里的问题是项目名称将是动态的。它可能是 或 .prj-eng-h-nc-raw-1637
prj-eng-p-nc-oauth-2218
我也尝试使用 rfind(),我们可以在其中找到子字符串的开头并替换,但这无济于事。
任何人都可以帮我解决问题。
{
"jobs": [],
"error": "Unable to process the request",
"msg": "400 Bad int64 value: prj-eng-d-nc-prcd-1077\n\nLocation: us-central1\nJob ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873\n"
}
输入为:
msg = "400 Bad int64 value: prj-eng-d-nc-prcd-1077\n\nLocation: us-central1\nJob ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873\n"
输出应为:
msg = "400 Bad int64 value: \n\nLocation: us-central1\nJob ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873\n"
答:
0赞
Tanishq Chaudhary
10/21/2023
#1
您正在寻找 Python 的正则表达式。
使用 ,我们可以将 替换为 中的 。re.sub(pattern, replacement, string)
pattern
replacement
string
以下代码演示了它的用法,前提是部分保持不变。prj-eng-d-nc
import re
msg = "text before prj-eng-d-nc-raw-1637 text after"
pattern = r"prj-eng-d-nc-\w*-\d*"
# replacing the pattern with empty string if matched
msg = re.sub(pattern, "", msg)
0赞
Hermann12
10/21/2023
#2
一个没有正则表达式魔术的解决方案的例子 l:
msg = "400 Bad int64 value: prj-eng-d-nc-prcd-1077\n\nLocation: us-central1\nJob ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873\n"
start = "400 Bad int64 value:"
end = "\n\nLocation:"
# find the index
front = msg.find(start)+len(start)
back = msg.find(end)
# slice via index
new_msg = msg[:front] + msg[back+1:]
print(new_msg)
输出:
400 Bad int64 value:
Location: us-central1
Job ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873
或者,您可以在一行中使用 . print(repr(new_msg))
1赞
Tusher
10/21/2023
#3
若要从自定义异常类中的字符串中删除动态子字符串,可以使用正则表达式来匹配子字符串并将其替换为空字符串。
import re
class CustomException(Exception):
def __init__(self, msg):
# Remove project name from error message
project_name_pattern = r'prj-eng(-\w+)*-\d+'
self.msg = re.sub(project_name_pattern, '', msg)
#Example
try:
raise CustomException('400 Bad int64 value: prj-eng-d-nc-prcd-1077\n\nLocation: us-central1\nJob ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873\n')
except CustomException as e:
print(e.msg)
评论