简体   繁体   English

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

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

I am trying to use REGEX to parse a gherkin file. 我正在尝试使用REGEX来解析一个小黄瓜文件。 I have successfully split it into multiple REGEX's to accomplish what I want, but I am having a problem getting the last instance of one of the Values. 我已成功将其拆分为多个REGEX以完成我想要的操作,但是在获取其中一个值的最后一个实例时遇到了问题。

(?s)(?P<Then>Then.*?)Scenario:|$ returns all instances except the last from (?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

The last 最后

Then Application will deny login
    And inform of no connection

Doesn't get selected. 没有被选中。 I have tried various things, but can't seem to get it. 我尝试了各种方法,但似乎无法理解。 Any suggestions? 有什么建议么?

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

Brief 简要

Right now your regex is saying: Match either (?P<Then>Then.*?)Scenario: or $ , you need to group all options together as shown below. 现在,您的正则表达式说:匹配(?P<Then>Then.*?)Scenario:$ ,您需要将所有选项组合在一起,如下所示。

Code

See regex in use here 查看正则表达式在这里使用

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

You can also use the s modifier ( re.DOTALL ) instead of placing it in the regex as (?s) . 您也可以使用s修饰符( re.DOTALL ),而不是将其作为(?s)放在正则表达式中。

Regular expressions is a very tempting tool when it comes to parsing data. 在解析数据时,正则表达式是一个非常诱人的工具。 But, some data has a pre-defined structure and format rules. 但是,某些数据具有预定义的结构和格式规则。 And, most importantly, existing parsers. 而且,最重要的是,现有的解析器。

In your case, these are the BDD Gherkin feature files. 就您而言,这些是BDD Gherkin feature文件。 behave library has an already existing parser - install behave , import and use it, sample: 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