【问题标题】:Match string from beginning to end of stringPython Regex:Findall从字符串的开头到结尾匹配字符串
【发布时间】:2021-11-06 06:17:48
【问题描述】:

text = "A random\string here"
test = re.findall('(?<=A ).+\s', text)

我只想打印从“A”结尾(不包括空格)到字符串结尾的所有内容。

我只想得到“随机\字符串”

【问题讨论】:

  • 把预期的输出,为什么你用“这个”?
  • 1) 不要使用str 作为变量名,它是内置的,2) re.findall(r'A\s+(.+)', text)re.findall(r'^A\s+(.+)', text)
  • 我试过 re.findall(r'^A\s+(.+)', text) 但这不起作用,因为在这种情况下它也会打印“这里”这个词

标签: python regex findall


【解决方案1】:

如果你想要一些简单的东西,我建议使用 split 而不是正则表达式(类似于 ‍‍test=text.split('A')[1]

如果你真的想使用正则表达式,你可以使用这种网站来调试它:https://regex101.com/

【讨论】:

    【解决方案2】:

    使用

    import re
    text = "A random\string here"
    match = re.search('^A\s+(.+)\s', text)
    if match:
        print(match.group(1))
    else:
        print(None)
    

    你会收到random\string

    Python proof

    解释

    --------------------------------------------------------------------------------
      ^                        the beginning of the string
    --------------------------------------------------------------------------------
      A                        'A'
    --------------------------------------------------------------------------------
      \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                               more times (matching the most amount
                               possible))
    --------------------------------------------------------------------------------
      (                        group and capture to \1:
    --------------------------------------------------------------------------------
        .+                       any character except \n (1 or more times
                                 (matching the most amount possible))
    --------------------------------------------------------------------------------
      )                        end of \1
    --------------------------------------------------------------------------------
      \s                       whitespace (\n, \r, \t, \f, and " ")
    

    【讨论】:

      【解决方案3】:

      您尝试的模式的问题是您使用了\s。您可以做的是将其断言到右侧。

      请注意,\s 也可以匹配换行符。

      (?<=A ).+(?=\s)
      

      查看regex demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-03
        • 1970-01-01
        • 2012-09-13
        • 2018-02-24
        • 1970-01-01
        • 2016-12-07
        相关资源
        最近更新 更多