Search code examples
robotframework

How can I do to extract a pattern in RobotFramework?


I have that kind of string :

"car model-8789 blue green"
"car model-879 blue green"
"car model-87897189 blue green"

And what I want is to extract model-xxxx where x are the numbers. I thought to split every string and to do a if and then using a regex but I wonder if there is a better solution to do that directly using RobotFramework ?

Thank you very much !


Solution

  • If you need to do string manipulation there usually are no easy ways around it. In this case, if the formatting is reliable, you can get by relatively easily. But if its not, then you'll either need some regexp or for-loops to find that data reliably.

    You should only need to split the string once, no regexp needed. You'll need to use String Library and Collections Library.

    *** Settings ***
    Library    BuiltIn
    Library    Collections
    
    *** Test Cases ***
    Get Model From Line
        ${STRING}=    Set Variable    car model-8789 blue green
        @{LINE}=    Split String    ${STRING}    ${SPACE}    # = ['car', 'model-8789', 'blue', 'green']
        FOR    ${WORD}    IN    @{LINE}
            IF    'model' in ${WORD}
                ${MODEL}=    Set Variable    ${WORD}
                Exit For Loop
            END
        END
        Log    ${MODEL}
    

    If possible you might want to look for a way to make the input in some structured format, like csv, to make this more robust.