Regex返回文本文件中以特定模式开头的行



我的文本文件:

--- config-archive/2022-12-21/R1.txt
+++ new
@@ -1,6 +1,6 @@
Building configuration...

-Current configuration : 1106 bytes
+Current configuration : 1089 bytes
!
version 12.4
service timestamps debug datetime msec
@@ -94,7 +94,7 @@
!
!
!
-banner motd ^Cthis is changed through config pushing script^C
+banner motd ^Cyoyoyoyo i just changed this^C
!
line con 0
exec-timeout 0 0

我需要程序从文本文件中返回以单个-或+开头的行。

我的方法是遍历文件并搜索模式作为字符串,我不认为这是有效的。所以需要正则表达式以一种有效的方式来做。谢谢你。

试试这个:

import re
pattern = r'^[-+](?![-+])'  # Match lines that start with a single `-` or `+` and do not have a `- and +` immediately after
with open('your_text_file.txt', 'r') as f:
for line in f:
if re.match(pattern, line):
print(line)

这听起来很像AB问题,但这里是您使用RegEx的解决方案:

^[-+].+

  • ^:匹配行起始
  • [-+]:匹配负号或正号
  • .+:匹配在
  • 行结束之前的任何字符

考虑只使用Python -它可能更快,而且肯定更容易阅读:

data = " ... "
lines = [line for line in data.splitlines()
if line.startswith('+') or line.startswith('-')]

最新更新