英文:
Removing sensitive informations from the logs using regex
问题
在我的Ruby应用程序中,我有以下正则表达式,可以帮助我从日志中删除敏感信息:
/(\\"|")secure[^:]+:\s*.*?/
当日志中包含以下信息时,它起作用:
{"secure_data": "Test"}
但是,当日志中有对象而不是字符串时,它不起作用:
{"secure_data": {"name": "Test"}}
如何更新正则表达式以处理这两种情况?
https://rubular.com/r/h9EBZot1e7NUkS
英文:
In my Ruby app I have the following regex that helps me with removing sensitive informations from logs:
/(\\"|")secure[^:]+:\s*.*?/
It works when in logs are the following information:
{"secure_data": "Test"}
but when instead of string I have object in logs it does not work:
{"secure_data": {"name": "Test"}}
How can I update regex to work with both scenarios?
答案1
得分: 1
以下内容应该适用于您想要做的事情。我建议使用 JSON 解析器。
{"secure[^:]*?:\s({?(?:(?:,[^"]*?)?"[^"]*?"(?::\s"[^"]*?")?)*?)*?}?}
使用这个正则表达式,secure_data 中的对象也可以包含多个键值对(字符串)。它仍然会匹配。其他对象将不会。
英文:
The following should work for what you're trying to do. I'd suggest using a json parser though.
{"secure[^:]*?:\s({?(?:(?:,[^"]*?)?"[^"]*?"(?::\s"[^"]*?")?)*?)*?}?}
With this regex the object in secure_data may also contain multiple key-value(string)-pairs. It will still match. Other objects will not.
答案2
得分: 1
你可以使用带有否定字符类和交替的正则表达式:
"secure[^:]+:\s*(?:"[^"]*"|{[^}]*})
在非捕获组 (?:"[^"]*"|{[^}]*})
中,我们匹配了一个带有引号的字符串或以 {
开始并以 }
结束的对象。
英文:
You may use this regex with negated character classes and an alternation:
"secure[^:]+:\s*(?:"[^"]*"|{[^}]*})
Inside non-capturing group (?:"[^"]*"|{[^}]*})
we are matching a quoted string or an object that starts with {
and ends with }
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论