获取数据仅以 space 正则表达式 - Python 开头

get data only start with space Regex - Python

我希望所有行都以 space

开头

初始文本示例:

!
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('line\scon(?s).*?(?=^\w)', str(abovetext))

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

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

此代码将遍历文本,并检查行中的第一个元素是否等于空字符串,这与 space.

相同

使用

(?m)^line\scon.*(?:\n .+)*

regex proof

解释

--------------------------------------------------------------------------------
  (?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'^line\scon.*(?:\n .+)*', str(abovetext), re.M)