【问题标题】:I am trying to parse string from python regex-Not able get desired output我正在尝试从 python 正则表达式解析字符串-无法获得所需的输出
【发布时间】:2020-09-02 12:49:46
【问题描述】:
sample_string = ":61:2002190219C45612.4S202EXC:OL3654628815//CT56748005:86:/BENM/Unitech Imports/REM//58970.047:61:2002190219C30000S103LCADV5674920204//CT56748006:86:/BENM/Gravity Imports/REM//INV:/FEB20/446301:61:2002190219C45612.4S202EXCOL3654628825//CT56748005:60F:61:2002190219C45612.4S202EXCOL3654628815//CT56748018"

基本上我都需要

1. :61:, :86: string which are next to each other any where in the full message ex:- re.findall()=expected o/p - [':61:2002190219C45612.4S202EXC:OL3654628815//CT56748005:86:/BENM/Unitech Imports/REM//58970.047', :61:2002190219C30000S103LCADV5674920204//CT56748006:86:/BENM/Gravity Imports/REM//INV:/FEB20/446301] 
i have below regex for above case which is working fine, can we simplify a bit, 
61:(?:[\w /,.-]|:(?!61:|86:))*:86:(?:[A-Za-z0-9 /.-]|:(?!61:|86:))*
regex example - https://regex101.com/r/U3MWF7/4

2. All :61 string which are not followed by :86 anywhere in the full message, ex:- re.findall()=
expected o/p=[':61:2002190219C45612.4S202EXCOL3654628825//CT56748005',':61:2002190219C45612.4S202EXCOL3654628815//CT56748018']

I have below regex to get all :61 strings from message which is not giving correct result - its giving all :61 strings which are followed by:86 also.
61:(?:[\w /,.-]|:(?!61:|86:))*(?!:86:)* ()
regex example - https://regex101.com/r/2svNjG/1

我尝试了多个选项,但无法获得所需的输出。寻求帮助

【问题讨论】:

标签: python regex


【解决方案1】:

您可以匹配 :61: 并断言右边的内容不包含 :86: 然后匹配直到下一次出现 :61: 通过匹配 [\w /.-] 中列出的一个或匹配 :不直接跟61:

:61:(?!.*:86:)(?:[\w /.-]|:(?!61:)[\w /.-]*)*

Regex demo | Python demo

如果有多行,您可以使用re.DOTALL 或使用内联修饰符(?s) 使点匹配换行符

(?s):61:(?!.*:86:)(?:[\w /.-]|:(?!61:)[\w /.-]*)* 

【讨论】:

  • 这包括:60F:,这是不同的字符串。 :61:2002190219C45612.4S202EXCOL3654628825//CT56748005 :60F:
  • @Navneet 所以你不想包括一个 6 后跟一个数字和可选的字符 A-Z? regex101.com/r/DzoIcc/1 或字符 a-z 或数字 regex101.com/r/Flrlq7/1
  • 不匹配完整字符串regex101.com/r/Flrlq7/1
  • @Navneet 完整字符串是什么意思?你得到了 2 个想要的匹配,对吗?
  • 谢谢@第四只鸟,仍然有一些字符串不匹配,但您已经给出了足够的指示。我会看看谢谢:)
猜你喜欢
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多