python如何使用正则写一个匹配空行的代码
时间: 2024-04-30 18:24:01 浏览: 9
你好,以下是 Python 正则匹配空行的代码示例:
```
import re
text = "line1\n\nline3\nline4\n\n"
pattern = r'\n\s*\n'
result = re.findall(pattern, text)
print(result)
```
输出结果为:
```
['\n\n', '\n\n']
```
这个正则表达式可以匹配连续两个换行符之间任意个数的空白符号,即匹配空行。希望能对你有所帮助。现在请你问我下一个问题。
相关问题
Python使用正则表达式匹配字符串结尾
使用正则表达式匹配字符串结尾可以使用$符号。$符号匹配字符串的末尾。
示例代码:
```python
import re
string = "Hello World!"
pattern = r"World!$"
match = re.search(pattern, string)
if match:
print("字符串以 'World!' 结尾")
else:
print("字符串不以 'World!' 结尾")
```
输出:
```
字符串以 'World!' 结尾
```
在正则表达式中,$符号也可以用于匹配空行。例如,r"^$"匹配空行。
Python用正则表达式删除空行
可以使用re模块的sub函数,将连续的多个空行替换成一个空行,从而删除空行。示例代码如下:
```python
import re
text = """
Hello
World
!
"""
pattern = r"\n+"
result = re.sub(pattern, "\n", text)
print(result)
```
输出结果为:
```
Hello
World
!
```
其中,`\n+`是匹配连续多个换行符的正则表达式,`sub`函数将其替换成一个换行符。注意,为了保证替换后的文本和原文本一致,需要在最后加上一个换行符。