正则表达式:如果之前找到其他文本则不匹配

Regex : Don't match if other text is found before

我正在尝试使用正则表达式解析降价文档以查找文档中是否有标题 (# title)。 我已经设法用这个正则表达式 (?m)^#{1}(?!#) (.*) 实现了这一点,问题是我也可以在我的降价中有代码部分,在那里我可以遇到 # title 格式作为评论。

我的想法是尝试找到 # 标题,但如果在前几行中有 ``` 语言,则不匹配。

这是一个文本示例,我只需要匹配 # my title 而不是下面的 # helloworld.py,特别是如果缺少 # my title(这是我需要找出的) :

<!--
.. title: Structuring a Python application
.. medium: yes
.. devto: yes
-->

# my title

In this short article I will explain all the different ways of structuring a Python application, from a quick script to a more complex web application.

## Single python file containing all the code


```python
#!/usr/bin/env python
# helloworld.py

test

这是三个正则表达式的任务。用第一个暂时屏蔽所有代码片段,用第二个处理markdown,用第三个取消屏蔽代码。

“筛选”是指将代码片段存储在字典中,并用字典键替换为一些特殊的markdown。

这对于正则表达式来说可能会变得非常混乱。但是因为看起来你无论如何都会使用 python - 这可能是微不足道的。

mkdwn = '''<!--
.. title: Structuring a Python application
.. medium: yes
.. devto: yes
-->

# my title

In this short article I will explain all the different ways of structuring a Python application, from a quick script to a more complex web application.

## Single python file containing all the code


```python
#!/usr/bin/env python
# helloworld.py

test'''

'''Get the first occurrence of a substring that
you're 100% certain **will not be present** before the title 
but **will be present** in the document after the title (if the title exists)
'''
idx = mkdwn.index('```')

# Now, try to extract the title using regex, starting from the string start but ending at `idx`
title_match = re.search(r'^# (.+)', mkdwn[:idx],flags=re.M)
# Get the 1st group if a match was found, else empty string
title = title_match.group(1) if title_match else ''
print(title)

你也可以减少这个

title_match = re.search(r'^# (.+)', mkdwn[:idx],flags=re.M)
# Get the 1st group if a match was found, else empty string
title = title_match.group(1) if title_match else ''

变成一个班轮,如果你喜欢那种东西-

title = getattr(re.search(r'^# (.+)', mkdwn[:idx],flags=re.M), 'group', lambda _: '')(1)

getattr 将 return 属性 group 如果存在(即找到匹配时) - 否则它只会 return 那个虚拟函数(lambda _: '') 它接受一个伪参数和 returns 一个空字符串,分配给 title.

然后使用参数 1 调用 returned 函数,如果找到匹配项,return 是第一组。如果未找到匹配项,那么参数并不重要,它只是 return 一个空字符串。

输出

my title