简体   繁体   English

正则表达式提取JSON中的字符

[英]Regex to extract characters within json

What would be the best regex to extract the following: 什么是提取以下内容的最佳正则表达式:

s = '":"1434919817660.wFzJl5KnFq1tyg5X0juKeQmbW8A="'
==> 14349198.17660.wFzJl5KnFq1tyg5X0.juKeQmbW8A=

It is a string between either a ' or " with length > 5 and that is terminated by ' or " . 它是介于" > '"长度> 5 "之间的字符串,并以'"结尾。 The best I could get was: 我能得到的最好的是:

>>> re.search(r'''[\'|\"](.+)[\'+\"]''', x).group(1)
':"1434919817660.wFzJl5KnFq1tyg5X0juKeQmbW8A='

You can use re.sub 您可以使用re.sub

>>> re.sub(r'[":]', '', s)
'1434919817660.wFzJl5KnFq1tyg5X0juKeQmbW8A='

If you are going to replace use str.translate: 如果要替换,请使用str.translate:

s = '":"1434919817660.wFzJl5KnFq1tyg5X0juKeQmbW8A="'

if len(s) > 5:
    print(s.translate(None,""":"'"""))
1434919817660.wFzJl5KnFq1tyg5X0juKeQmbW8A=

For python3 you need to create a mapping using the ord of the characters you want to replace: 对于python3,您需要使用要替换的字符的ord创建映射:

s = '":"1434919817660.wFzJl5KnFq1tyg5X0juKeQmbW8A="'

print(s.translate({ord('"'):"",ord("'"):"",ord(":"):""}))

If you have json you could also extract by key, if it were json though you would not have any ' . 如果您有json,也可以按键提取,如果它是json,尽管您不会有任何'

You could also try doing an string replace here: 您也可以尝试在此处进行字符串replace

s.replace('"','').replace(':','').replace("'",'').strip()
14349198.17660.wFzJl5KnFq1tyg5X0.juKeQmbW8A=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM