Reputation: 7581
How can I access matching groups in regular expressions?
For example: ${line} = Set variable String with-8
How could I grab the 'String with' part and the number part in seperate variables?
I tried:
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
Upvotes: 0
Views: 1395
Reputation: 3737
The main problem on your test is the missing import of module re
in the Evaluate
keyword. I also corrected the input string, and this is your working test:
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
This is the output it produces with 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
But Robot Framework includes some keywords for Regular Expressions in the String library. See below a full working example:
*** 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
This is the output it produces with 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
Upvotes: 5