【问题标题】:Regex match until any characters are found except for the word 'and'正则表达式匹配,直到找到除单词'and'之外的任何字符
【发布时间】:2020-10-06 02:26:44
【问题描述】:

我想找到一个正则表达式解决方案来匹配项目编号之后的字符串的一部分,直到找到任何字符,除非它是单词'and'

s = 'this part 123 should be ignored Item Number(s)92349252 and 30239429434, 124029354,345340332,  234325923 hallo 2121124'

如果我特别添加hallo,它会起作用

re.match(r'.*?Item Number\(s\)(.*?)hallo.*$', s).group(1)
'92349252 and 30239429434, 124029354,345340332,  234325923 '

但是我希望它适用于任何字符(包括hallo),除非它是单词and

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您不需要正则表达式,只需使用:

    a,b,c = s.partition("and")
    print(c)
    

    c 是 and 之后的部分。

    【讨论】:

    • 我想要一个正则表达式的通用解决方案,它也应该适用于s = 'this part 123 should be ignored Item Number(s)92349252 and 30239429434, 124029354,345340332 and 234325923 hallo 2121124'
    • 试试吧,这将在第一个分区,并且对双方都有效
    【解决方案2】:

    我们可以尝试使用字符串拆分与re.findall 的组合。首先,拆分文本Item Number(s) 上的输入,并在数组中保留second 条目。这对应于Item Number(s) 右侧的所有文本。然后,使用re.split 分割空格,后面跟一些内容不是 单词and、数字、空格或逗号。最后,使用re.findall 捕获剩余文本中的所有数字。

    s = 'this part 123 should be ignored Item Number(s)92349252 and 30239429434, 124029354,345340332,  234325923 hallo 2121124'
    nums = re.findall(r'\b\d+\b', re.split(r' (?!\band\b|[\d\s,])', s.split('Item Number(s)')[1])[0])
    print(nums)
    
    ['92349252', '30239429434', '124029354', '345340332', '234325923']
    

    【讨论】:

    • 啊,但诀窍是我不想要hallo 之后的数字,只想要Number(s)hallo 之间的数字(或除and 之外的任何其他字符)。
    • @Bruno 检查更新的答案。你的问题没有把这个要求说得很清楚。
    • 感谢您的输入,但我不想在“你好”处特别拆分,但对于任何字符,除非这些字符构成单词and。因此,例如 123 Item Number(s) 456 and 789 @ 0123 产生 `456 和 789 `。
    • 尝试更新后的答案,它将re.split 与您的新逻辑结合使用。
    【解决方案3】:

    我错误地陈述了这个问题。正确的问题是:在 Item Number(s) 之后找到一个包含数字的字符串,直到找到一个单词,除非这个单词是 and

    改写:查找Item Number(s) 之后的字符串,该字符串有 1 个或多个数字,由零个或多个非单词字符分隔,或重复单词 'and',前面有一个非单词字符,后跟 0 个或多个非单词字符

    import re
    s = '123 ignore Item Number(s)92349252 and,,;^and,and;;;30239429434, 124029354,345340332,  and and 234325923 hallo 2121124'
    pattern = r'.*?Item Number\(s\)(((\W*?|(\W+?and)+\W*?)\d+)+)'
    m = re.match(pattern, s).group(1)
    numbers = re.findall('\d+', m)
    print(numbers)
    

    ['92349252', '30239429434', '124029354', '345340332', '234325923']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2011-10-13
      • 2011-12-13
      相关资源
      最近更新 更多