【问题标题】:Getting "hello" from "1. hello" with Regex [closed]使用正则表达式从“1. hello”中获取“hello”[关闭]
【发布时间】:2020-10-06 23:43:22
【问题描述】:

我只是在学习正则表达式,我无法从列表中获取单词

来自如下列表:

[ "1. hello - jeff", "2. gello - meff", "3. fellow - gef", "12. willow - left"]

我想检索单词:“hello”、“gello”、“fellow”和“willow”

到目前为止,这是我的简化代码

for i in [ARRAY OF LISTED WORDS]:
  word = re.findall(r'^((?![0-9]?[0-9]. ))\w+', i)
  print(word)

老实说尝试了很多组合,在网上找不到我理解的好文章。提前致谢!

【问题讨论】:

  • 这能回答你的问题吗? Learning Regular Expressions
  • @ggorlen 我试过 r"\w+",我只得到数字:"1."、"2."、"3."等等。你的第二个建议让我得到了同样的结果。我希望我做对了。
  • @CurtisHu 不要在 ggorlen 中列出。我不确定他的模式会达到什么效果。我已经在下面发布了答案。 stackoverflow.com/a/64235386/2847946
  • @MarkMoretto,您可能没有意识到 OP 改变了他们的要求。查看编辑历史。据你所知,它会再次改变。 OP 需要完全澄清他们的规范,否则这个问题基本上是无法回答的,除了幸运的猜测。
  • 感谢您指出这一点。我仍然看不到 "\w+" 将如何跳过:字符串 "1.hello" 中的数值、句点和空格以仅捕获 "hello"。

标签: python python-3.x regex


【解决方案1】:

您正在寻找一个或多个非空格 ('\S+') 数字后跟一个句点后跟一个空格 ('\d+\.\s') 和一个空格后跟一个破折号 (@ 987654323@):

pattern = r'\d+\.\s(\S+)\s-'
[re.findall(pattern, l)[0] for l in your_list]

【讨论】:

    【解决方案2】:

    你的正则表达式模式:

    pattern = r"""
        \d+     # 1 or more digits
        \.      # Escaped period character
        \s+?    # 1 or more whitespace
        (\w+)   # 1 or more alphabetic characters
        \s+     # 1 or more whitespace
        -       # hyphen
        .*      # zero or more of anything besides newline.
    """
    

    字符串列表:

    words = [ "1. hello - jeff", "2. gello - meff", "3. fellow - gef", "12. willow - left"]
    
    
    for word in words:
        # capture results in a variable
        # re.X for verbose pattern format.
        tmp = re.search(pattern, word, flags = re.X)
        # If variable is not None, print results of the first captured group.
        if tmp:
            print(tmp.group(1))
    

    输出:

    hello
    gello
    fellow
    willow
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 2023-02-12
      • 2012-10-17
      • 2021-03-25
      • 2013-07-31
      • 2021-02-07
      • 2020-05-10
      相关资源
      最近更新 更多