无法泛化正则表达式。

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

can't generalize regex expression

问题

我正在编写一个正则表达式来从我的日志中提取一些数据。

所以我写了几行Python代码

import re

text = ",\\\"authorization\\\":\\\"Bearer xxxxxx.yyyyy.fff-dddd\\\","
match = re.search(r"authorization\\\":\\\"([^\\\"]+)", text)

if match:
    authorization_string = match.group(1)
    print(authorization_string)


text = ",\\\"authorization\\\":\\\"xxxxxx.yyyyy.fff-dddd\\\","
match = re.search(r"authorization\\\":\\\"([^\\\"]+)", text)

if match:
    authorization_string = match.group(1)
    print(authorization_string)

这个输出是我需要的,即

Bearer xxxxxx.yyyyy.fff-dddd
xxxxxx.yyyyy.fff-dddd

如果我在regex中尝试似乎不起作用

如果我使用

https://regex101.com/r/R7Oz9J/1

成功抓取一个情况,但我想找到一个表达式,即使字符串 "Bearer " 不存在也能抓取令牌。

英文:

I am writing a regex expression to reduct some data from my logs.

so I wrote a few Python lines

import re

text = ",\\\"authorization\\\":\\\"Bearer xxxxxx.yyyyy.fff-dddd\\\","
match = re.search(r"authorization\\\":\\\"([^\\\"]+)", text)

if match:
    authorization_string = match.group(1)
    print(authorization_string)


text = ",\\\"authorization\\\":\\\"xxxxxx.yyyyy.fff-dddd\\\","
match = re.search(r"authorization\\\":\\\"([^\\\"]+)", text)

if match:
    authorization_string = match.group(1)
    print(authorization_string)

The output of this is what I need, i.e.

Bearer xxxxxx.yyyyy.fff-dddd
xxxxxx.yyyyy.fff-dddd

If I try in regex does not seem to work

If I use

https://regex101.com/r/R7Oz9J/1

manage to grab one case, but I would like to find an expression that is able to grab the token even if the string "Bearer " is missing.

答案1

得分: 1

我能够使您指定的两种情况都能正常工作,具体如下:

/"authorization\\\\/":"(.+)\\\\/"/gm

您可以在此处查看工作示例:链接

英文:

I was able to get both cases that you specified working with the following:

/"authorization\\\\\\\":\\\\\\"(.+)\\\\\\"/gm

You can see the working example here.

huangapple
  • 本文由 发表于 2023年6月8日 21:19:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76432273.html
匿名

发表评论

匿名网友

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

确定