【发布时间】:2021-10-11 21:55:38
【问题描述】:
我想使用正则表达式匹配以下文本:
x-xxxxxx23 w44jrflsdhdsls 2021-10-09 02:46:37,371 - mycode - ERROR - Error in mycode interaction
Traceback (most recent call last):
File "mycode.py", line 83, in upload_detection_image
put_response = s3_object.put(Body=image, ContentType="image/jpeg")
File "/usr/local/lib/python3.6/dist-packages/boto3/resources/factory.py", line 520, in do_action
response = action(self, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/boto3/resources/action.py", line 83, in __call__
response = getattr(parent.meta.client, operation_name)(*args, **params)
File "/usr/local/lib/python3.6/dist-packages/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/usr/local/lib/python3.6/dist-packages/botocore/client.py", line 676, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ExpiredToken) when calling the PutObject operation: The provided token has expired.
我可以匹配从第二行开始的所有内容:
query = re.compile(
rf"^Traceback(.*?){re.escape('botocore.exceptions.ClientError: An error occurred (ExpiredToken) when calling the PutObject operation: The provided token has expired.')}(.*?)\n",
flags=re.DOTALL | re.MULTILINE)
但我也尝试匹配新的第一行我没有得到任何匹配:
query = re.compile(
rf"^(.*?){re.escape('Error in mycode')}(.*?)Traceback(.*?){re.escape('botocore.exceptions.ClientError: An error occurred (ExpiredToken) when calling the PutObject operation: The provided token has expired.')}(.*?)\n",
flags=re.DOTALL | re.MULTILINE),
该文本是较大文本的一部分,我使用以下方法查找匹配项:
matches = [match for match in pattern.finditer(text)]
谢谢
编辑:我可以确认以下内容与从 Error in mycode 开始的所有内容匹配:
rf"{re.escape('Error in S3')}(.*?)Traceback(.*?){re.escape('botocore.exceptions.ClientError: An error occurred (ExpiredToken) when calling the PutObject operation: The provided token has expired.')}(.*?)\n",
flags=re.DOTALL | re.MULTILINE)
【问题讨论】:
-
我建议尝试一些更简单的方法。如果你这样做
re.compile('Error in mycode')会发生什么?这与第一行匹配吗?现在逐渐增加更多复杂性以查看它匹配的内容,直到它与您认为的不匹配。 -
见上面的详细信息:)
-
如果您能够在代码方面进行更改,我建议使用 try-catch 块包装该逻辑并捕获 botocore 异常。以这种方式从错误对象中提取数据应该很简单。
-
这可能会有所帮助:stackoverflow.com/questions/587345/…