【发布时间】:2016-09-09 05:53:23
【问题描述】:
我想用、->、=> 或用多个空格包裹的字符串拆分字符串,这意味着我可以从以下字符串中获得两个项目she 和he正在拆分:"she he", "she he", "she he ", "she he ", "she->he", "she ->he", "she=>he", "she=> he", " she-> he ", " she => he \n"
我试过用这个:
re.compile("(?<!^)((\\s*[-=]>\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split(' she -> he \n')
我得到的是一个包含四个项目的列表:[' she', ' -> ', ' -> ', 'he \n']。
为此,
re.compile("(?<!^)((\\s*[-=]>\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split('she he')
我明白了:['she', ' ', None, 'he']。
为什么有四个项目?没有中间的两个,我怎么能只得到两个?
【问题讨论】:
-
split保留捕获组的内容。使它们全部不被捕获。 -
在将字符串传递给 pattern.split 之前,您不能执行 string.strip() 吗?让它更干净一点。
-
尝试使用
re.findall(...):re.findall('\w+', " she -> he \n")将提供['she', 'he']。 -
根据documentation on re.split:
If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.@Rawing 向您解释了原因。您的模式相当复杂,因此除非您真的需要如此严格的检查,否则通过 pre-strip() 使用更简单的正则表达式的方法可能更可取。