Filed under: Cucumber, — Tags: Cucumber-JVM, Regular expression — Thomas Sundberg — 2016-04-02
If you are like me, then you will feel a lump in your stomach when you realize that you need a regular expression. I think that the saying "If you have a problem that requires a regular expression, then you have two problems" is very appropriate most of the time.
It turns out that you need a some regular expressions when you are working with Cucumber. In this case, they are usually not very complicated.
Here is a table with the regular expressions that I use. Those that I use for parameter matching are in regular expression groups, that is with a parenthesis pair. They are exclusively used to map parts of Gherkin to method parameters.
|(.*)||Match any string|
|(\\d+)||Match any number|
|^||Any beginning of a string|
|$||Any end of a string|
Ok, that wasn't much. Four different expressions. Two of them are used for matching parameters and two of them are used to match any ending of a string.
^ and the dollar sign
$ is suggested in the code snippets Cucumber suggests
when a step is missing. I just use them although they may not strictly be needed in all cases.
(\\d+) whenever it finds a number in a scenario. This leaves you to
(.*). That is something even I was able to learn.
You can obviously use more complicated expressions, but I find that these are are enough for me. You match either strings or digits. Everything could be matched as strings but that would force you to parse the strings with the risk errors popping up unnecessary late.