【问题标题】:Regular Expression Split on character not in Qualified String (python)正则表达式拆分字符不在限定字符串中(python)
【发布时间】:2015-04-01 13:02:43
【问题描述】:

我可以使用一些对熟悉的人来说可能很容易的事情的帮助。我正在尝试将一些更多/更少的商店酿造的配置文件解析为字典/json。我有一些使用字符串过程或 re.split() 的 python 代码,它适用于我测试过的所有内容;但是,我知道有些极端情况可能会破坏它,我想创建通用正则表达式来更好地处理逻辑,因此相同的正则表达式可以移植到其他语言(perl、awk、C等)我们在工作中使用来帮助我们保持一致。

我希望在 Python 中使用 re.match() 或 re.split()。

我正在寻找的模式应该执行以下操作:

1) 在第一个上拆分一个 str ?如果 ?不在由单引号和/或双引号限定的子字符串中。

strIn:
'''
foo = 'some',"stuff?",'that "could be?" nested?', ? but still capture this? and "this?"
'''

listOut
['''foo = 'some',"stuff?",'that "could be?" nested?', ''' , ''' but still capture this? and "this?"''']

2) 如果 # 不在由单引号或双引号限定的子字符串中,并且 # 不在第一个不合格的子字符串之后,则在第一个 # 上拆分一个 str ? (根据 1)

strIn:
'''
foo = 'some',"stuff?#, maybe 'nested#' " # #but now this is all a comment to capture ,'that "could be?#" nested#', ? but still capture this?! and "this?! "
'''

listOut:
['''foo = 'some',"stuff?#, maybe 'nested#' " ''', ''' #but now this is all a comment to capture ,'that "could be?#" nested#', ? but still capture this?! and "this?! "'''

【问题讨论】:

  • 如果您尝试过,请添加您的尝试
  • 问一个问题。你的输入让我很困惑。发布实际输入。

标签: python regex string parsing


【解决方案1】:

你可以使用re.split

>>> s = '''foo = 'some',"stuff?",'that "could be?" nested?', ? but still capture this? and "this?"'''
>>> [i for i in re.split(r'^((?:"[^"]*"|\'[^\']*\'|[^\'"?])*)\?', s) if i]
['foo = \'some\',"stuff?",\'that "could be?" nested?\', ', ' but still capture this? and "this?"']

re.findall.

>>> re.findall(r'^((?:"[^"]*"|\'[^\']*\'|[^\'"?])*)\?(.*)', s)
[('foo = \'some\',"stuff?",\'that "could be?" nested?\', ', ' but still capture this? and "this?"')]
>>> [j for i in re.findall(r'^((?:"[^"]*"|\'[^\']*\'|[^\'"?])*)\?(.*)', s) for j in i]
['foo = \'some\',"stuff?",\'that "could be?" nested?\', ', ' but still capture this? and "this?"']

DEMO

你可以对第二个问题做同样的事情。

>>> s = '''foo = 'some',"stuff?#, maybe 'nested#' " # #but now this is all a comment to capture ,'that "could be?#" nested#', ? but still capture this?! and "this?! "'''
>>> [j for i in re.findall(r'^((?:"[^"]*"|\'[^\']*\'|[^\'"#])*)#(.*)', s) for j in i]
['foo = \'some\',"stuff?#, maybe \'nested#\' " ', ' #but now this is all a comment to capture ,\'that "could be?#" nested#\', ? but still capture this?! and "this?! "']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多