获取数据只能从空间Regex-Python开始



我想让所有行都以空格开头

初始文本示例:

!
line con 0
session-timeout 5 
exec-timeout 5 0
password 7 1239211A43054F0202D1D
transport output none
line 2
no activation-character
no exec
transport preferred none
transport output pad telnet rlogin lapb-ta mop udptn v120 ssh
stopbits 1
line vty 0 4
session-timeout 5 
access-class 125 in
exec-timeout 5 0
length 0
transport input ssh
transport output none

结果必须是:

line con 0
session-timeout 5 
exec-timeout 5 0
password 7 1239211A43054FB202D1D
transport output none

我在Python中尝试了一些东西

result = re.findall('linescon(?s).*?(?=^w)', str(abovetext))

使用

(?m)^linescon.*(?:n .+)*

请参阅正则表达式证明。

解释

--------------------------------------------------------------------------------
(?m)                     set flags for this block (with ^ and $
matching start and end of line) (case-
sensitive) (with . not matching n)
(matching whitespace and # normally)
--------------------------------------------------------------------------------
^                        the beginning of a "line"
--------------------------------------------------------------------------------
line                     'line'
--------------------------------------------------------------------------------
s                       whitespace (n, r, t, f, and " ")
--------------------------------------------------------------------------------
con                      'con'
--------------------------------------------------------------------------------
.*                       any character except n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
(?:                      group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
n                       'n' (newline)
--------------------------------------------------------------------------------
' '
--------------------------------------------------------------------------------
.+                       any character except n (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
)*                       end of grouping

Python代码:

result = re.findall(r'^linescon.*(?:n .+)*', str(abovetext), re.M)

字符串是可迭代的,可以通过索引访问

lines=[]
for line in text:
if line[0] == ' ':
lines.append(line)

此代码将对文本进行迭代,并检查行中的第一个元素是否等于一个空字符串,该字符串与空格相同。

最新更新