gpt4 book ai didi

python - 如何用正则表达式进行模式替换?

转载 作者:行者123 更新时间:2023-12-04 08:07:21 26 4
gpt4 key购买 nike

我想在这个字符串中匹配“windowsXP”:

windowsXP|7|8 
或者
windowsXP 7 8
我写了一个模式来匹配它:
 ([^0-9|])+[0-9\.]+.*
为什么不匹配?这是|在支架上制造麻烦。我试图逃避它,但它也没有奏效。
([^0-9\|])+[0-9\.]+.*

最佳答案

看:

  • ([^0-9|])+查找不同于数字和管道的字符
  • [0-9\.]+尝试匹配数字或句点,但存在表达式无法捕获的管道。

  • ^([^|\s]+)[|\s](\d+)[|\s](\d+)
    proof
    说明
    --------------------------------------------------------------------------------
    ^ the beginning of the string
    --------------------------------------------------------------------------------
    ( group and capture to \1:
    --------------------------------------------------------------------------------
    [^|\s]+ any character except: '|', whitespace (1 or more
    times (matching the most amount
    possible))
    --------------------------------------------------------------------------------
    ) end of \1
    --------------------------------------------------------------------------------
    [|\s] any character of: '|', whitespace (\n, \r,
    \t, \f, and " ")
    --------------------------------------------------------------------------------
    ( group and capture to \2:
    --------------------------------------------------------------------------------
    \d+ digits (0-9) (1 or more times (matching
    the most amount possible))
    --------------------------------------------------------------------------------
    ) end of \2
    --------------------------------------------------------------------------------
    [|\s] any character of: '|', whitespace (\n, \r,
    \t, \f, and " ")
    --------------------------------------------------------------------------------
    ( group and capture to \3:
    --------------------------------------------------------------------------------
    \d+ digits (0-9) (1 or more times (matching
    the most amount possible))
    --------------------------------------------------------------------------------
    ) end of \3
    Python code :
    import re
    regex = r"^([^|\s]+)[|\s](\d+)[|\s](\d+)"
    test_str = "windowsXP|7|8"
    print(re.findall(regex, test_str))
    结果 : [('windowsXP', '7', '8')]

    关于python - 如何用正则表达式进行模式替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66163952/

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