Behave – Regular Expressions
”;
Let us have an overall view of the syntax of regular expressions −
-
Dot (.) − Equivalent to any character.
-
Caret (^) − Equivalent to beginning of string. (^…)
-
Dollar Sign ($) − Equivalent to end of string. (…$)
-
| − Expression x| y, matches x or y.
-
− Escape character.
-
. − Matches dot. (.)
-
\ − Matches backslash. ()
-
[…] − Declares a set of characters. ([A-Za-z])
-
d − Matches digit. ([0-9])
-
D − Matches non-digit.
-
s − Matches whitespace character.
-
S − Matches non – whitespace character.
-
w − Matches alphanumeric.
-
W − Matches non-alphanumeric.
-
(…) − Group a pattern of regular expression.
-
number − Matches text of previous group by index. (1)
-
(? P<name>…) − Matches pattern and stores it in the name parameter.
-
(?P=name) − Matches all text which was matched by the previous group name.
-
(?:…) − Matches a pattern, however cannot capture text.
-
(?#…) − Comment (not considered). Narrates details of pattern.
In case a character, character set or group needs to repeat multiple times, it is mandatory to provide the cardinality of the pattern of regular expression.
-
? : Pattern having cardinality 0… 1:not mandatory(question mark)
-
– : Pattern having cardinality 0 or more, 0..( asterisk)
-
+ – : Pattern having cardinality 1 or more, 1..(plus)
-
{n}: Matches a pattern for n repetitions.
-
{a ,b}: Matches from a to b for a pattern repetitions.
-
[A-Za-z]+ : Matches multiple alphabetical characters.
There are maybe steps in the feature file having almost the similar phrases. Behave has the parsing ability. The method use_step_parser is used for this and we have to pass the parser type as a parameter to that method.
For regular expression matchers, we have to pass the parameter re. The parameter (? P<name>…) is utilised to obtain parameters from the step definition.
Feature File (almost similar steps)
The feature file for similar steps is as follows −
Feature − Payment Process Scenario − Check Debit transactions Given user is on "debit" screen Scenario − Check Credit transactions Given user is on "credit" screen
Corresponding Step Implementation File
The step implementation file is as follows −
from behave import * #define parser type use_step_matcher("re") #regular expression parsing @given(''user is on "(?P<payment>.*)" screen'') def step_impl(context, payment): print("Screen type: ") print(payment)
Output
The output obtained after running the feature file is as follows. Here, we have used the command behave –no-capture -f plain.
The output shows the debit and credit. These two values have been passed with almost the similar steps in the feature file. In step implementation, we have parsed both the steps with regular expression.
”;