英文:
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 = '{% set name = "testDB" %}'
text2 = '{% set version = "0.0.1" %}'
pattern = re.compile(r'(?<=").+?(?=")')
for text in text1, text2:
print(pattern.findall(text))
Output:
['testDB']
['0.0.1']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论