Rogger Fernandes
Rogger Fernandes

Reputation: 73

Retrieve variables Regex Python

Is there a way of retrieving a pattern inside a regular expression in Python? eg.:

strA = '\ta -- b'

and I would like to retrieve 'a' and 'b' into different variables

Upvotes: 0

Views: 53

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 30985

You can't retrieve a pattern, you can match or retrieve a capturing group content matching your pattern.

Following your example:

\ta -- b

If you want to retrieve the content you can use capturing groups using parentheses like:

\t(a) -- (b)

Regular expression visualization

The regex explanation for this is:

\t                       '\t' (tab)
(                        group and capture to \1:
  a                        'a'
)                        end of \1
 --                      ' -- '
(                        group and capture to \2:
  b                        'b'
)                        end of \2

Then you would be able to grab group content by accesing then through its index like \1 (or $1) and group \2 (or $2). But you are going to grab the matched content, not the pattern itself.

So, if you have:

\t(\w) -- (\d)

Regular expression visualization

You would grab content that matches that pattern:

\t                       '\t' (tab)
(                        group and capture to \1:
  \w                       word characters (a-z, A-Z, 0-9, _)
)                        end of \1
 --                      ' -- '
(                        group and capture to \2:
  \d                       digits (0-9)
)                        end of \2

But you can't retrieve \w or \d itself.

If you want to get the patterns for this:

\t\w -- \d

You should split above string by -- and you would get strings::

"\t\w "
" \d"

Upvotes: 0

alecxe
alecxe

Reputation: 473823

Sounds like you are talking about saving/capturing groups:

>>> import re
>>> pattern = r"\t(\w+) -- (\w+)"
>>> s = '       test1 -- test2'
>>> a, b = re.search(pattern, s).groups()
>>> a
'test1'
>>> b
'test2'

Upvotes: 1

Related Questions