[英]Python Split string with a string that is on new line
我试图用一个单独在新行上的单词来分割一个字符串。
例如,每当我遇到“SPLIT”这个词时,我都想将字符串分成几部分。 对于我的用例,“SPLIT”这个词应该只在一个新行上单独出现:
我尝试str.split("\nSPLIT")
,但无法让它在单词之后起作用。
Hello there,
SPLIT
how are you?
应该返回 ["Hello there,", "how are you?"]
Hello there, SPLIT how are you?
应该返回 ["Hello there, SPLIT 你好吗?"]
Hello there,
SPLIT
应该返回 ["Hello there,", ""]
Hello there,
SPLIT how are you?
应该返回 ["Hello there,\nSPLIT 你好吗?"]
感谢帮助。
您可以使用
re.split(r'\n?^SPLIT$\n?', text, flags=re.M)
re.split(r'(?:^|\n)SPLIT(?:$|\n)', text)
请参阅Python 演示。
\n?^SPLIT$\n?
与re.M
标志一起使用的正则表达式匹配可选的换行符,然后确保索引位于行首( ^
),然后匹配并使用SPLIT
,然后检查SPLIT
之后是否有行尾 position 然后匹配可选的换行符。
(?:^|\n)SPLIT(?:$|\n)
正则表达式只匹配字符串开头或换行符, SPLIT
然后匹配字符串结尾或换行符。 请注意使用非捕获组,以避免将换行符或额外的空字符串作为结果列表的一部分。
请参阅正则表达式演示 #1和正则表达式演示 #2 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.