Python Forum
'|' character within Regex returns a tuple?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
'|' character within Regex returns a tuple?
#9
When you set up a capturing regex, it numbers the capturing parentheses from left to right. So in a pattern like this:
>>> re.findall(r"(\w+\d+\w+)|(\d+\w+\d+)", "AAA1AAA")
[('AAA1AAA', '')]
you get a tuple with each element being the capture from each capture group.

It's not the pipe character, it's the parentheses.

Even if only one can match, they're still numbered and set from left to right. So the group you get back is a tuple with all the capture groups. To find what's in there, you can either loop through the elements of the tuple, or you can rewrite the regex so there's only one (or zero) capture groups.

If the parenthesis starts with ?:, then it won't be a capture group. That allows the pattern match to go back to "the entire pattern" and you don't have a tuple any longer.

>>> re.findall(r"(?:\w+\d+\w+)|(?:\d+\w+\d+)", "AAA1AAA")
['AAA1AAA']
>>> re.findall(r"(?:\w+\d+\w+)|(?:\d+\w+\d+)", "111A111")
['111A111']
pprod likes this post
Reply


Messages In This Thread
RE: '|' character within Regex returns a tuple? - by bowlofred - Feb-19-2021, 05:16 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How returns behave in a function with multiple returns? khasbay 1 835 May-19-2024, 08:48 AM
Last Post: deanhystad
  Regex: a string does not starts and ends with the same character Melcu54 5 3,626 Jul-04-2021, 07:51 PM
Last Post: Melcu54
  [solved] unexpected character after line continuation character paul18fr 4 6,936 Jun-22-2021, 03:22 PM
Last Post: deanhystad
  code with no tuple gets : IndexError: tuple index out of range Aggam 4 4,442 Nov-04-2020, 11:26 AM
Last Post: Aggam
  SyntaxError: unexpected character after line continuation character siteshkumar 2 4,193 Jul-13-2020, 07:05 PM
Last Post: snippsat
  Regex won't replace character with line break Tomf96 2 3,430 Jan-12-2020, 12:14 PM
Last Post: Tomf96
  how can i handle "expected a character " type error , when I input no character vivekagrey 2 3,597 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  Substitution with regular expression returns hidden character SOH bajacri 2 4,840 Nov-17-2019, 03:38 AM
Last Post: bajacri
  How to get first line of a tuple and the third item in its tuple. Need Help, Anybody? SukhmeetSingh 5 4,368 May-21-2019, 11:39 AM
Last Post: avorane
  Replace changing string including uppercase character with lowercase character silfer 11 8,554 Mar-25-2019, 12:54 PM
Last Post: silfer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020