英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论