如何在机器人框架中使用正则表达式选择子字符串

Cro*_*nax 4 regex string substring robotframework

在名为String的Robot Framework库中,有几个关键字允许我们使用regexp来操作字符串,但这些操作似乎不包括从字符串中选择子字符串.

为了澄清,我打算有一个价格,即€ 1234,00我想从中选择仅4个主要数字,这意味着我留下了1234(我将转换为int以用于验证计算).我有一个正则表达式,允许我这样做,如下所示:

(\d+)[\.\,]

如果我使用Remove String Using Regexp这个正则表达式,我将完全保留我试图删除的内容.如果我使用Get Lines Matching Regexp,我将得到整行,而不仅仅是我想要的结果,如果我使用Get Regexp Matches我会得到正确的结果,除了它将在列表中,然后我将不得不再次操作,这样看起来似乎没有最佳.

我是否只是错过了允许我这样做的关键字,或者我被迫编写自己的自定义关键字,让我这样做?我有点惊讶这个功能似乎不可用,因为这是我想到的第一个用例,当我想到使用带有字符串的正则表达式时......

Bry*_*ley 7

您可以使用Evaluate关键字运行一些python代码.

例如:

| Using 'Evaluate' to find a pattern in a string
| | ${string}= | set variable | € 1234,00
| | ${result}= | evaluate | re.search(r'\\d+', '''${string}''').group(0) | re
| | should be equal as strings | ${result} | 1234
Run Code Online (Sandbox Code Playgroud)

从机器人框架2.9开始,有一个名为Get regexp matches的关键字,它返回所有匹配项的列表.

例如:

| Using 'Get regexp matches' to find a pattern in a string
| | ${string}= | set variable | € 1234,00
| | ${matches}= | get regexp matches | ${string} | \\d+
| | should be equal as strings | ${matches[0]} | 1234
Run Code Online (Sandbox Code Playgroud)