簡體   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