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

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

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:

  1. import re
  2. pattern = r'{% (\w+)\s*=\s*"(.*?)" %}'
  3. text = '{% set name = "testDB" %}'
  4. match = re.search(pattern, text)
  5. if match:
  6. key = match.group(1)
  7. value = match.group(2)
  8. print("key:", key)
  9. print("value:", value)
  10. else:
  11. 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?

  1. text1 = '{% set name = "testDB" %}'
  2. 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:

  1. import re
  2. pattern = r"^{% (\w+)\s*=\s*'(.*?)' %}$"
  3. text = '{% set name = "testDB" %}'
  4. match = re.search(pattern, text)
  5. if match:
  6. key = match.group(1)
  7. value = match.group(2)
  8. print("key:", key)
  9. print("value:", value)
  10. else:
  11. print("No match found.")

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

答案1

得分: -2

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

  1. import re
  2. text1 = '{% set name = "testDB" %}'
  3. text2 = '{% set version = "0.0.1" %}'
  4. pattern = re.compile(r'(?<=").*?(?=")')
  5. for text in text1, text2:
  6. print(pattern.findall(text))

输出:

  1. ['testDB']
  2. ['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:

  1. import re
  2. text1 = &#39;{% set name = &quot;testDB&quot; %}&#39;
  3. text2 = &#39;{% set version = &quot;0.0.1&quot; %}&#39;
  4. pattern = re.compile(r&#39;(?&lt;=&quot;).+?(?=&quot;)&#39;)
  5. for text in text1, text2:
  6. print(pattern.findall(text))

Output:

  1. [&#39;testDB&#39;]
  2. [&#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:

确定