pandas正则表达式匹配两组空格之间的所有项目

时间:2017-03-29 01:27:49

标签: python python-3.x pandas

如何匹配所有内容以在左侧正好3个空格和冒号右侧正好3个空格之间包含特殊字符?示例用W表示为空白区域。

示例匹配:

\\s\\s\\sdata\\sstuff:\\s\\sfound\\ssome([%$)Data\\sas\\swhiteSpace\\s\\s\\s
   data stuff:  found some([%$)Data as whiteSpace   

示例nonMatch:

\\s\\sdata\sstuff:\\s\\sfound\\sno\\sdatacause\\sno\\s3\\sspaces\\sbefore\\sor\\safter\\s\\s
  data stuff:  found no datacause no 3 spaces before or after   

目的是将其扩展为从pandas数据帧的单个列中分隔列。

预期产出:

data stuff                                data stuff 2
found some([%$)Data as whiteSpace         if i had more examples for data stuff 2 it would show here
extra random data to add into a outputdf  if i had more examples for data stuff 2 it would show here

最初的想法是使用这样的东西,但这不起作用。

"(\\s\\s\\s(.*?)\\:\\s\\s(.*?)\\s\\s\\s)"

2 个答案:

答案 0 :(得分:1)

考虑这个df

DBCC DROPCLEANBUFFERS

Regex1:

    col
0   data stuff:   found   some([%$)Data as whiteSpace   1

将返回

df.col.str.extract(':\\s{3}(.*)\s{3}')

这是发现之前三个空格之间的内容,以及1之前结束时的三个空格。

在哪里

0    found   some([%$)Data as whiteSpace
Name: col, dtype: object

将返回

df.col.str.extract(':\\s{3}(.*?)\s{3}') #note the ? after .*

这是三个空格的第一个和第二个实例之间的内容。

如果您提供更多测试用例,那么您将需要正则表达式做什么,这将很清楚。

答案 1 :(得分:0)

(?:^|[^ ])   (.*?)   (?:$|[^ ])

分解!

  • (?:^|[^ ]) - 匹配任何空格或 行开头
  • x (.*?) x匹配两边3个空格之间的任何内容(x' s添加,因此空格不会消失)
  • (?:$|[^ ])匹配空格或行末 的任何内容

Example in regexr