Robotframework - 访问正则表达式匹配组

tm1*_*701 0 robotframework

如何访问正则表达式中的匹配组?

例如:${line} = Set variable String with-8

我怎么能在单独的变量中获取“String with”部分和数字部分?

我试过:

Test case determining strings and number
    ${line} =   Set variable  String with-8
    ${resultRegexp} =  Evaluate  re.search('(.+)\\-(\\d+)', '''${line}''')
    Log  The string(s) part is: ${resultRegexp[0]   # or group(1) or so
    Log  The number part is: ${resultRegexp[1]   # or group(2) or so
Run Code Online (Sandbox Code Playgroud)

小智 5

在测试中的主要问题是模块的缺失进口reEvaluate关键字。我还更正了输入字符串,这是您的工作测试:

Test case determining strings and number
    ${line} =    Set variable    String with-8
    ${resultRegexp}=    Evaluate    re.search("(.*)\\-(\\d+)", "${line}"), re
    Log    The string(s) part is: ${resultRegexp[0].group(1)}    # or group(1) or so
    Log    The number part is: ${resultRegexp[0].group(2)}    # or group(2) or so

Run Code Online (Sandbox Code Playgroud)

这是它使用 RIDE 生成的输出:

Starting test: Test Regular Exp.Test case determining strings and number
20201004 18:16:32.817 :  INFO : ${line} = String with-8
20201004 18:16:32.819 :  INFO : ${resultRegexp} = (<re.Match object; span=(0, 13), match='String with-8'>, <module 're' from '/usr/lib64/python3.8/re.py'>)
20201004 18:16:32.821 :  INFO : The string(s) part is: String with
20201004 18:16:32.822 :  INFO : The number part is: 8
Ending test: Test Regular Exp.Test case determining strings and number
Run Code Online (Sandbox Code Playgroud)

但是 Robot Framework 在 String 库中包含了一些正则表达式的关键字。请参阅下面的完整工作示例:

*** Settings ***
Library           String

*** Test Cases ***
Test case determining strings and number
    ${line} =    Set variable    String with-8
    ${resultRegexp}=    String.Get Regexp Matches    ${line}    (.*)\\-(\\d+)    1    2
    Log    The string(s) part is: ${resultRegexp[0][0]}    # First element of tuple
    Log    The number part is: ${resultRegexp[0][1]}    # Second element of tuple
Run Code Online (Sandbox Code Playgroud)

这是它使用 RIDE 生成的输出:

Starting test: Test Regular Exp.Test case determining strings and number
20201004 18:28:36.606 :  INFO : ${line} = String with-8
20201004 18:28:36.609 :  INFO : ${resultRegexp} = [('String with', '8')]
20201004 18:28:36.611 :  INFO : The string(s) part is: String with
20201004 18:28:36.612 :  INFO : The number part is: 8
Ending test: Test Regular Exp.Test case determining strings and number
Run Code Online (Sandbox Code Playgroud)