Python:基于条件拆分,但只拆分条件的一部分

2024-09-27 02:14:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字符串

random_string = '12:58 PM word \n12:20PM person \n12:39PM'

I am doing the following:
re.split(r'[\n]+\d',random_string)

And I get:
['12:58 PM word ', '2:20PM person ', '2:39PM']

But I want:
['12:58 PM word ', '12:20PM person ', '12:39PM']

你知道怎么做吗?你知道吗


Tags: andthe字符串regetstringrandomam
2条回答

https://docs.python.org/2/library/re.html

(?=...) Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

所以,在你的情况下:

>>> re.split(r'[\n]+(?=\d)', '12:58 PM word \n12:20PM person \n12:39PM')
['12:58 PM word ', '12:20PM person ', '12:39PM']

在regex中使用lookahead避免在换行后匹配数字:

>>> random_string = '12:58 PM word \n12:20PM person \n12:39PM'
>>> re.split(r'\n+(?=\d)', random_string)
['12:58 PM word ', '12:20PM person ', '12:39PM']
  • 正则表达式\n+(?=\d)将在换行符上拆分,当一个数字正好位于换行符之后。你知道吗
  • 无需将\n放入character类。你知道吗

相关问题 更多 >

    热门问题