繁体   English   中英

正则表达式查找字符串的最后一个实例

[英]Regex to find the last instance of a string

我正在尝试使用REGEX来解析一个小黄瓜文件。 我已成功将其拆分为多个REGEX以完成我想要的操作,但是在获取其中一个值的最后一个实例时遇到了问题。

(?s)(?P<Then>Then.*?)Scenario:|$返回除最后一个实例外的所有实例。

# This is a sample .feature file
Feature: Authorized Logins

Users will have individual logins, gated by passwords.


Scenario: Invalid login credentials are entered

    Given Default Database is loaded
    And App is available and running
    When User enters invalid login
    Then Application should deny login

Scenario: Valid login credentials are entered

    Given Default Database is loaded
    And App is available and running
    When User enters valid login
    And display test case selection screen
    Then Application should grant login
    And display test case selection screen

Scenario: No database connection
    Given Database is stopped
    And App is available and running
    When User enters valid login
    Then Application will deny login
    And inform of no connection

最后

Then Application will deny login
    And inform of no connection

没有被选中。 我尝试了各种方法,但似乎无法理解。 有什么建议么?

https://regex101.com/r/iiM5X5/2

简要

现在,您的正则表达式说:匹配(?P<Then>Then.*?)Scenario:$ ,您需要将所有选项组合在一起,如下所示。

查看正则表达式在这里使用

(?P<Then>Then.*?)(?:Scenario:|$)

您也可以使用s修饰符( re.DOTALL ),而不是将其作为(?s)放在正则表达式中。

在解析数据时,正则表达式是一个非常诱人的工具。 但是,某些数据具有预定义的结构和格式规则。 而且,最重要的是,现有的解析器。

就您而言,这些是BDD Gherkin feature文件。 behave有一个已经存在的解析器-安装behave ,导入并使用它,示例:

from behave.parser import Parser

filename = "test.feature"
with open(filename) as f:
    feature = Parser().parse(f.read(), filename)

    print(feature.name)
    for scenario in feature.scenarios:
        print(scenario.name)
        print("-----")
        for step in scenario.steps:
            print(step.keyword, step.name)
        print("--------")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM