如何在Python中使用正则表达式提取给定代码中的键和值对?

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

How to extract key and value pairs using regular expressions in Python for given code?

问题

Sure, here's the translated code snippet with the corrected regular expression pattern:

import re

pattern = r'{% (\w+)\s*=\s*"(.*?)" %}'
text = '{% set name = "testDB" %}'

match = re.search(pattern, text)

if match:
    key = match.group(1)
    value = match.group(2)
    print("key:", key)
    print("value:", value)
else:
    print("No match found.")

This code should correctly extract the key and value from the given text variable.

英文:

How can I parse this code with regular expressions in Python?

text1 = '{% set name = "testDB" %}'
text2 = '{% set version = "0.0.1" %}'

I need output as in form of key and value where I can store
key_text1 = set name and value_text1 = testDB.
Similarly for text2, key_text2 = set version and `value_text2 = 0.0.1

the code I tried is follow:

import re

pattern = r"^{% (\w+)\s*=\s*'(.*?)' %}$"
text = '{% set name = "testDB" %}'


match = re.search(pattern, text)

if match:
    key = match.group(1)
    value = match.group(2)
    print("key:", key)
    print("value:", value)
else:
    print("No match found.")

and the output am getting here is No match found instead key and value

答案1

得分: -2

根据所显示的数据,看起来您想要从字符串中提取两个双引号之间的内容。如果是这样的话,以下是代码的翻译部分:

import re

text1 = '{% set name = "testDB" %}'
text2 = '{% set version = "0.0.1" %}'

pattern = re.compile(r'(?<=").*?(?=")')

for text in text1, text2:
    print(pattern.findall(text))

输出:

['testDB']
['0.0.1']
英文:

Given the data shown, it appears that you want to isolate whatever's between two double-quotes in the string. If that's the case then:

import re

text1 = &#39;{% set name = &quot;testDB&quot; %}&#39;
text2 = &#39;{% set version = &quot;0.0.1&quot; %}&#39;

pattern = re.compile(r&#39;(?&lt;=&quot;).+?(?=&quot;)&#39;)

for text in text1, text2:
    print(pattern.findall(text))

Output:

[&#39;testDB&#39;]
[&#39;0.0.1&#39;]

huangapple
  • 本文由 发表于 2023年5月24日 17:44:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76322165.html
匿名

发表评论

匿名网友

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

确定