python - re.split() 给出列表中的空元素

标签 python regex

请帮忙解决这个问题:

m = re.split('([A-Z][a-z]+)', 'PeopleRobots')
print (m)

结果:

['', 'People', '', 'Robots', '']

为什么列表中有空元素?

最佳答案

根据 re.split documentation :

If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the end of the string:

如果你想得到PeopleRobots,使用re.findall :

>>> re.findall('([A-Z][a-z]+)', 'PeopleRobots')
['People', 'Robots']

您可以省略分组:

>>> re.findall('[A-Z][a-z]+', 'PeopleRobots')
['People', 'Robots']

关于python - re.split() 给出列表中的空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18124254/

相关文章:

javascript - RegEX 将 <div/foo> 替换为 </div>

jquery - 使用 jQuery 或 RegEx 获取在样式表中写入的 CSS 值

ios - 我必须使用正则表达式来提取消息还是有属性?

python - 在 Django 中迭代数据库列

python - 如何对多个角色使用 discord.py remove_roles? (作为参数的对象列表)

python - 在无法容纳内存的大文件中查找字符串的出现

regex - "[[]]"在正则表达式中是什么意思?

python2.7 - 从充满 unicode 的 .txt 文件中读取字典

python - 在 Rust 中使用 python 的多处理库

javascript - YouTube 视频能否仅由数字组成,如果可以,如何匹配不仅由数字组成的字符串?