【问题标题】:Python regex does not find the pattern to parse markdown python code while regex101 doesPython regex 找不到解析 markdown python 代码的模式,而 regex101 可以
【发布时间】:2023-01-13 01:21:25
【问题描述】:
在降价文件中,我想提取 python 代码
```python
...
```(end)
使用正则表达式和 python。
虽然python代码
import re
text = 'We want to examine the python code\n\n```python\ndef halloworld():\n\tfor item in range(10):\n\t\tprint("Hello")\n``` and have no bad intention when we want to parse it'
findpythoncodepattern = re.compile(r'```python.+```',re.MULTILINE)
for item in findpythoncodepattern.finditer(text):
print(item)
找不到结果(即使我添加或删除 re.MULTILINE 标志),正则表达式似乎不是问题,因为 Regex101 找到了它。
当我改变文本成一个生的文本' '->r' ',它找到了一些东西但不是完全匹配。这里有什么问题?
【问题讨论】:
标签:
python
regex
python-re
【解决方案1】:
尝试使用flags = re.S(又名re.DOTALL):
import re
text = 'We want to examine the python code
```python
def halloworld():
for item in range(10):
print("Hello")
``` and have no bad intention when we want to parse it'
findpythoncodepattern = re.compile(r"```python.+```", flags=re.S)
for item in findpythoncodepattern.finditer(text):
print(item.group(0))
印刷:
```python
def halloworld():
for item in range(10):
print("Hello")
```
【解决方案2】:
在降价文件中,我想提取 python 代码
要仅提取代码,请使用 (?<=```python)([sS]+)(?=```) 模式。
import re
text = 'We want to examine the python code
```python
def halloworld():
for item in range(10):
print("Hello")
``` and have no bad intention when we want to parse it'
pattern = re.compile(r'(?<=```python)([sS]+)(?=```)')
for item in pattern.findall(text):
print(item)
# def halloworld():
# for item in range(10):
# print("Hello")
笔记:[sS] 与带有 re.S 标志的 . 相同。