python中的多行模式匹配
定期计算机生成的消息(简化):
Hello user123,
- (604)7080900
- 152
- minutes
Regards
使用 python,如何在之间提取“(604)7080900”、“152”、“分钟”(即遵循前导 "- "
模式的任何文本)两个空行(空行是“Hello user123”之后的 \n\n
和“Regards”之前的 \n\n
)。如果结果字符串列表存储在数组中就更好了。谢谢!
编辑:两个空白行之间的行数不固定。
第二次编辑:
例如
hello
- x1
- x2
- x3
- x4
- x6
morning
- x7
world
x1 x2 x3 很好,因为所有行都被 2 个空行包围,出于同样的原因,x4 也很好。 x6 不好,因为它后面没有空白行,x7 不好,因为它前面没有空白。 x2 很好(不像 x6、x7),因为前面的线是好线,后面的线也很好。
当我发布问题时,这个条件可能不清楚:
a continuous of good lines between 2 empty lines
good line must have leading "- "
good line must follow an empty line or follow another good line
good line must be followed by an empty line or followed by another good line
谢谢
A periodic computer generated message (simplified):
Hello user123,
- (604)7080900
- 152
- minutes
Regards
Using python, how can I extract "(604)7080900", "152", "minutes" (i.e. any text following a leading "- "
pattern) between the two empty lines (empty line is the \n\n
after "Hello user123" and the \n\n
before "Regards"). Even better if the result string list are stored in an array. Thanks!
edit: the number of lines between two blank lines are not fixed.
2nd edit:
e.g.
hello
- x1
- x2
- x3
- x4
- x6
morning
- x7
world
x1 x2 x3 are good, as all lines are surrounded by 2 empty lines, x4 is also good for the same reason. x6 is not good because no blank line follows it, x7 is not good as no blank in front of it. x2 is good (not like x6, x7) because the line ahead is a good line and the line following it is also good.
this conditions might be not clear when I posted the question:
a continuous of good lines between 2 empty lines
good line must have leading "- "
good line must follow an empty line or follow another good line
good line must be followed by an empty line or followed by another good line
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的方法是遍历这些行(假设您有一个行列表或一个文件,或者将字符串拆分为一个行列表),直到看到一行
'\n'
,然后检查每一行是否以'- '
开头(使用startswith
字符串方法)并将其切片,存储结果,直到找到另一个空行。例如:编辑:由于您详细说明了您想要执行的操作,因此这里是循环的更新版本。它不再循环两次,而是收集数据直到遇到“坏”行,并在遇到块分隔符时保存或丢弃收集的行。它不需要显式迭代器,因为它不会重新启动迭代,因此您只需向它传递一个行列表(或任何可迭代的)即可:
这里它正在运行:
The simplest approach is to go over these lines (assuming you have a list of lines, or a file, or split the string into a list of lines) until you see a line that's just
'\n'
, then check that each line starts with'- '
(using thestartswith
string method) and slicing it off, storing the result, until you find another empty line. For example:Edited: Since you elaborate on what you want to do, here's an updated version of the loops. It no longer loops twice, but instead collects data until it encounters a 'bad' line, and either saves or discards the collected lines when it encounters a block separator. It doesn't need an explicit iterator, because it doesn't restart iteration, so you can just pass it a list (or any iterable) of lines:
And here it is in action:
这样做:
并这样做:
do this:
and have this: