黄瓜正则表达式:如何匹配逗号分隔值对的重复模式?

时间:2011-04-21 11:40:52

标签: python regex cucumber bdd

我有以下字符串:

I submit the following values: username 'foo', password 'bar'
I submit the following values: username 'foo', password 'bar','foo', profile 'bar', extra 'something'

我正在尝试匹配值对,但我不确定如何重复模式。

所以我想要的结果是:

 username 'foo'
 password 'bar'
 ...

到目前为止我的正则表达式:

 I submit the following values: (\w+\s[^,]+),

我需要找到一种重复模式的方法,我还需要在最后处理丢失的逗号。我在Cucumber中使用结果,比如Python的测试框架(freshen)。

最终结果将是:

@When(r'I submit the following values: (\w+\s[^,]+), ...')
def post_values_to_url(*args):
    post_dict = {}
    for pairs in args:
         #add values to dict

    response = client.get('this/is/a/url', post_dict)

3 个答案:

答案 0 :(得分:2)

如果你需要能够解析任意数量的对,那么我建议使用一个表,例如:

When I submit the following values:
  | username | foo |
  | password | bar |

在Cucumber :: Ast :: Table上有一个rows_hash方法可以满足你的需要。

然而,我怀疑使用像这样的“一刀切”步骤定义会使您的场景难以阅读。相反,如何做这样的事情:

Given a user exists with username "foo"
And that user has the profile "bar"
When I login as "foo" with password "bar"
...

编辑:刚刚注意到你实际上并不是黄瓜。但我怀疑Freshen也会支持表格。

答案 1 :(得分:0)

围绕整个模式: (?:(\w+\s[^,]+),)+

答案 2 :(得分:0)

结束将其拆分为两个正则表达式:

@When(r'I submit the following values: (.+)')
def post_values_to_url(pairs):
    regex = r'(\w+)\s\'(\w+)\',?'
    results = re.findall(regex, pairs)
    post_dict = {}

    for result in results:
        post_dict[result[0]] = result[1]