使用正则表达式从日志中删除敏感信息

huangapple go评论60阅读模式
英文:

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?

https://rubular.com/r/h9EBZot1e7NUkS

答案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 }.

Update RegEx Demo

huangapple
  • 本文由 发表于 2020年1月3日 16:04:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定