gpt4 book ai didi

python - 正则表达式中的可选匹配

转载 作者:太空狗 更新时间:2023-10-30 01:57:12 25 4
gpt4 key购买 nike

尝试将这些输入字符串匹配到三个匹配组 (Regex101 link):

    | input string  | x  | y   | z  |
------------------------------------
I | a | a | | |
II | a - b | a | b | |
III | a - b-c | a | b-c | |
IV | a - b, 12 | a | b | 12 |
V | a - 12 | a | | 12 |
VI | 12 | | | 12 |

所以输入字符串的剖析如下:

  • optional first part with free text up until a hyphen with surrounding whitespace (-) or the input string ends
  • optional second part with any character after the first hyphen with surrounding whitespace up until a comma or the input string ends
  • optionally exactly two digits at the end

我尝试了很多不同的解决方案,这是我目前的尝试:

^(?P<x>.*)(?:-)(?P<y>.*)(?<!\d)(?P<z>\d{0,2})(?!\d)$

它处理场景 IIIVV OK(还必须对空白进行一些修剪),但是:

  • IVI 根本没有返回
  • III 不是在第一个连字符处拆分而是在最后一个连字符处拆分

最佳答案

这似乎做得相当不错:

^(?:(.*?)(?: - |$))?(?:(.*?)(?:, |$))?(\d\d$)?$

感兴趣的值将分别位于组 1、2 和 3 中。

唯一的罪魁祸首是“两位数”将是

  • 在案例 V 的第 2 组中,
  • 在案例 VI 的第 1 组中,

在这些情况下,其他组为空。

这是因为“两位数”与 “自由文本直到分隔符或字符串结束” 规则相匹配。

您可以使用否定前瞻强制将两位数放入最后一组,但除非“两位数”不是第 1 组和第 2 组的合法值,否则这是不正确的。在任何情况下,它都会使表达式变得笨拙:

^(?:((?!\d\d$).*?)(?: - |$))?(?:((?!\d\d$).*?)(?:, |$))?(\d\d$)?$

分割:

^                    # string starts(?:(.*?)(?: - |$))?  # any text, reluctantly, and " - " or the string ends(?:(.*?)(?:, |$))?   # any text, reluctantly, and ", " or the string ends(\d\d$)?             # two digits and the string ends$                    # string ends

关于python - 正则表达式中的可选匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43376074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com