Python 2.7 Regular Expressions

Non-special chars match themselves. Exceptions are special characters:

\ Escape special char or start a sequence.

. Match any char except newline, see re.DOTALL

^ Match start of the string, see re.MULTILINE

$ Match end of the string, see re.MULTILINE

[] Enclose a set of matchable chars

R|S Match either regex R or regex S.

() Create capture group, & indicate precedence

After '[', enclose a set, the only special chars are:

] End the set, if not the 1st char

  • A range, eg. a-c matches a, b or c

^ Negate the set only if it is the 1st char

Quantifiers (append '?' for non-greedy):

{m} Exactly m repetitions

{m,n} From m (default 0) to n (default infinity)

  • 0 or more. Same as {,}

  • 1 or more. Same as {1,}

? 0 or 1. Same as {,1}

Special sequences:

\A Start of string

\b Match empty string at word (\w+) boundary

\B Match empty string not at word boundary

\d Digit

\D Non-digit

\s Whitespace [ \t\n\r\f\v], see LOCALE,UNICODE

\S Non-whitespace

\w Alphanumeric: [0-9a-zA-Z_], see LOCALE

\W Non-alphanumeric

\Z End of string

\g<id> Match prev named or numbered group,

'<' & '>' are literal, e.g. \g<0>

or \g<name> (not \g0 or \gname)

Special character escapes are much like those already escaped in Python string literals. Hence regex '\n' is same as regex '\n':

\a ASCII Bell (BEL)

\f ASCII Formfeed

\n ASCII Linefeed

\r ASCII Carriage return

\t ASCII Tab

\v ASCII Vertical tab

\ A single backslash

\xHH Two digit hexadecimal character goes here

\OOO Three digit octal char (or just use an

initial zero, e.g. \0, \09)

\DD Decimal number 1 to 99, match

previous numbered group

Extensions. Do not cause grouping, except 'P<name>':

(?iLmsux) Match empty string, sets re.X flags

(?:...) Non-capturing version of regular parens

(?P<name>...) Create a named capturing group.

(?P=name) Match whatever matched prev named group

(?#...) A comment; ignored.

(?=...) Lookahead assertion, match without consuming

(?!...) Negative lookahead assertion

(?<=...) Lookbehind assertion, match if preceded

(?<!...) Negative lookbehind assertion

(?(id)y|n) Match 'y' if group 'id' matched, else 'n'

Flags for re.compile(), etc. Combine with '|':

re.I == re.IGNORECASE Ignore case

re.L == re.LOCALE Make \w, \b, and \s locale dependent

re.M == re.MULTILINE Multiline

re.S == re.DOTALL Dot matches all (including newline)

re.U == re.UNICODE Make \w, \b, \d, and \s unicode dependent

re.X == re.VERBOSE Verbose (unescaped whitespace in pattern

is ignored, and '#' marks comment lines)

Module level functions:

compile(pattern[, flags]) -> RegexObject

match(pattern, string[, flags]) -> MatchObject

search(pattner, string[, flags]) -> MatchObject

findall(pattern, string[, flags]) -> list of strings

finditer(pattern, string[, flags]) -> iter of MatchObjects

split(pattern, string[, maxsplit, flags]) -> list of strings

sub(pattern, repl, string[, count, flags]) -> string

subn(pattern, repl, string[, count, flags]) -> (string, int)

escape(string) -> string

purge() # the re cache

RegexObjects (returned from compile()):

.match(string[, pos, endpos]) -> MatchObject

.search(string[, pos, endpos]) -> MatchObject

.findall(string[, pos, endpos]) -> list of strings

.finditer(string[, pos, endpos]) -> iter of MatchObjects

.split(string[, maxsplit]) -> list of strings

.sub(repl, string[, count]) -> string

.subn(repl, string[, count]) -> (string, int)

.flags # int, Passed to compile()

.groups # int, Number of capturing groups

.groupindex # {}, Maps group names to ints

.pattern # string, Passed to compile()

MatchObjects (returned from match() and search()):

.expand(template) -> string, Backslash & group expansion

.group([group1...]) -> string or tuple of strings, 1 per arg

.groups([default]) -> tuple of all groups, non-matching=default

.groupdict([default]) -> {}, Named groups, non-matching=default

.start([group]) -> int, Start/end of substring match by group

.end([group]) -> int, Group defaults to 0, the whole match

.span([group]) -> tuple (match.start(group), match.end(group))

.pos int, Passed to search() or match()

.endpos int, "

.lastindex int, Index of last matched capturing group

.lastgroup string, Name of last matched capturing group

.re regex, As passed to search() or match()

.string string, "

Gleaned from the python 2.7 're' docs. http://docs.python.org/library/re.html

https://github.com/tartley/python-regex-cheatsheet Version: v0.3.3

Using variables with custom embedded argument regular expressions

Whenever custom embedded argument regular expressions are used, Robot Framework automatically enhances the specified regexps so that they match variables in addition to the text matching the pattern. This means that it is always possible to use variables with keywords having embedded arguments. For example, the following test case would pass using the keywords from the earlier example.

Using variables with custom regular expressions
Variable Value
${DATE} 2011-06-27
Test Case Step
Example I type ${1} + ${2}
Today is ${DATE}

A drawback of variables automatically matching custom regular expressions is that it is possible that the value the keyword gets does not actually match the specified regexp. For example, variable ${DATE} in the above example could contain any value and Today is ${DATE} would still match the same keyword.

Behavior-driven development example

The biggest benefit of having arguments as part of the keyword name is that it makes it easier to use higher-level sentence-like keywords when writing test cases in behavior-driven style. The example below illustrates this. Notice also that prefixes Given, When and Then are left out of the keyword definitions.

Embedded arguments used by BDD style tests
Test Case Step
Add two numbers Given I have Calculator open
When I add 2 and 40
Then result should be 42
Add negative numbers Given I have Calculator open
When I add 1 and -2
Then result should be -1
Keyword Action Argument Argument
I have ${program} open Start Program ${program}
I add ${number 1} and ${number 2} Input Number ${number 1}
Push Button +
Input Number ${number 2}
Push Button =
Result should be ${expected} ${result} = Get Result
Should Be Equal ${result} ${expected}

Note

Embedded arguments feature in Robot Framework is inspired by how step definitions are created in a popular BDD tool Cucumber.

2.6.5 User keyword return values

Similarly as library keywords, also user keywords can return values. Typically return values are defined with the [Return] setting, but it is also possible to use BuiltIn keywords Return From Keyword and Return From Keyword If. Regardless how values are returned, they can be assigned to variables in test cases and in other user keywords.

Using [Return] setting

The most common case is that a user keyword returns one value and it is assigned to a scalar variable. When using the [Return] setting, this is done by having the return value in the next cell after the setting.

User keywords can also return several values, which can then be assigned into several scalar variables at once, to a list variable, or to scalar variables and a list variable. Several values can be returned simply by specifying those values in different cells after the [Return] setting.

User keywords returning values using [Return] setting
Test Case Action Argument Argument Argument
One Return Value ${ret} = Return One Value argument
Some Keyword ${ret}
Multiple Values ${a} ${b} ${c} = Return Three Values
@{list} = Return Three Values
${scalar} @{rest} = Return Three Values
Keyword Action Argument Argument Argument
Return One Value [Arguments] ${arg}
Do Something ${arg}
${value} = Get Some Value
[Return] ${value}
Return Three Values [Return] foo bar zap

Using special keywords to return

BuiltIn keywords Return From Keyword and Return From Keyword If allow returning from a user keyword conditionally in the middle of the keyword. Both of them also accept optional return values that are handled exactly like with the [Return] setting discussed above.

The first example below is functionally identical to the previous [Return] setting example. The second, and more advanced, example demonstrates returning conditionally inside a for loop.

User keywords returning values using special keywords
Test Case Action Argument Argument Argument
One Return Value ${ret} = Return One Value argument
Some Keyword ${ret}
Advanced @{list} = Create List foo baz
${index} = Find Index baz @{list}
Should Be Equal ${index} ${1}
${index} = Find Index non existing @{list}
Should Be Equal ${index} ${-1}
Keyword Action Argument Argument Argument
Return One Value [Arguments] ${arg}
Do Something ${arg}
${value} = Get Some Value
Return From Keyword ${value}
Fail This is not executed
Find Index [Arguments] ${element} @{items}
${index}= Set Variable ${0}
:FOR ${item} IN @{items}
Return From Keyword If '${item}' == '${element}' ${index}
${index}= Set Variable ${index + 1}
Return From Keyword ${-1} # Could also use [Return]

Note

Both Return From Keyword and Return From Keyword If are available since Robot Framework 2.8.

2.6.6 User keyword teardown

Starting from Robot Framework 2.6, also user keywords may have a teardown. It is defined using [Teardown] setting.

Keyword teardown works much in the same way as a test case teardown. Most importantly, the teardown is always a single keyword, although it can be another user keyword, and it gets executed also when the user keyword fails. In addition, all steps of the teardown are executed even if one of them fails. However, a failure in keyword teardown will fail the test case and subsequent steps in the test are not run. The name of the keyword to be executed as a teardown can also be a variable.

User Keyword Action Argument Argument
With Teardown Do Something
[Teardown] Log keyword teardown
Using variables [Documentation] Teardown given as variable
Do Something
[Teardown] ${TEARDOWN}

results matching ""

    No results matching ""