python - 获取数据仅以空格正则表达式开头 - 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('line\scon(?s).*?(?=^\w)', str(abovetext))
解决方案
采用
(?m)^line\scon.*(?:\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
蟒蛇代码:
result = re.findall(r'^line\scon.*(?:\n .+)*', str(abovetext), re.M)
推荐阅读
- python - 可以将 Excel 选项卡读入代码并使用格式化写回相同的选项卡
- angular - 将一个组件返回到另一个组件内的模板
- php - laravel orm mult 在哪里覆盖条件
- java - KeyListener 错误 - 类不覆盖
- r - 数据表:通过检查多行上的多列来创建新列
- php - 基于 Woocommerce 中用户角色的运费折扣
- sql - 不包含指定表达式作为聚合视图的一部分 - 这是什么意思?
- javascript - 在画布(js)中超时改变的颜色/ setInterval 的问题
- maven - TomEE 7.0.5 - 正确排除 JSF 2.2 jar 并包含 JSF 2.3 jar
- git - 致命:请求的 URL 返回错误:403 权限被拒绝