【问题标题】:String split using regex with pattern present in text使用文本中存在模式的正则表达式拆分字符串
【发布时间】:2018-11-22 14:17:04
【问题描述】:

我有很多字符串需要用逗号分隔。示例:

myString = r'test,Test,NEAR(this,that,DISTANCE=4),test again,"another test"'
myString = r'test,Test,FOLLOWEDBY(this,that,DISTANCE=4),test again,"another test"'

我想要的输出是:

["test", "Test", "NEAR(this,that,DISTANCE=4)", "test again", """another test"""] #list length = 5

我不知道如何在一项中保留“this,that,DISTANCE”之间的逗号。我试过这个:

l = re.compile(r',').split(myString) # matches all commas
l = re.compile(r'(?<!\(),(?=\))').split(myString) # (negative lookback/lookforward) - no matches at all

有什么想法吗?假设允许的“函数”列表定义为:

f = ["NEAR","FOLLOWEDBY","AND","OR","MAX"]

【问题讨论】:

标签: python regex token


【解决方案1】:

你可以使用

(?:\([^()]*\)|[^,])+

the regex demo

(?:\([^()]*\)|[^,])+ 模式匹配括号之间的任何子字符串的一次或多次出现,其中没有() 或除, 之外的任何字符。

Python demo

import re
rx = r"(?:\([^()]*\)|[^,])+"
s = 'test,Test,NEAR(this,that,DISTANCE=4),test again,"another test"'
print(re.findall(rx, s))
# => ['test', 'Test', 'NEAR(this,that,DISTANCE=4)', 'test again', '"another test"']

【讨论】:

    【解决方案2】:

    如果要明确指定哪些字符串算作函数,则需要动态构建正则表达式。否则,请使用 Wiktor 的解决方案。

    >>> functions = ["NEAR","FOLLOWEDBY","AND","OR","MAX"]
    >>> funcs = '|'.join('{}\([^\)]+\)'.format(f) for f in functions)
    >>> regex = '({})|,'.format(funcs)
    >>>
    >>> myString1 = 'test,Test,NEAR(this,that,DISTANCE=4),test again,"another test"'
    >>> list(filter(None, re.split(regex, myString1)))
    ['test', 'Test', 'NEAR(this,that,DISTANCE=4)', 'test again', '"another test"']
    >>> myString2 = 'test,Test,FOLLOWEDBY(this,that,DISTANCE=4),test again,"another test"'
    >>> list(filter(None, re.split(regex, myString2)))
    ['test',
     'Test',
     'FOLLOWEDBY(this,that,DISTANCE=4)',
     'test again',
     '"another test"']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      相关资源
      最近更新 更多