Search code examples
pythonregexpython-3.11

Capturing data in regex in python 3.11


I've got the regex expression I want to use:

\*\*Suggested by \<\@(.*?)\> \(ID\: (.*?)\)\*\*\\n+(.*)$

along with a template string:

**Suggested by <@1234567890> (ID: 1234567890)**\n\ntesting new idea

This works when testing here: https://regex101.com - with a minor caveat (can't seem to disregard multiple new lines) reference however it can be skipped by replacing \n+ with \n\n

When trying to use this in python:

import re

user_input = '**Suggested by <@1234567890> (ID: 1234567890)**\n\ntesting new idea'
regex = re.compile(r'\*\*Suggested by \<\@(.*?)\> \(ID\: (.*?)\)\*\*\\n+(.*$)')
content = re.search(regex, user_input)
print(content.group(1))
print(content.group(2))
print(content.group(3))

I'm getting this error https://i.sstatic.net/FQyZa.png

I have tried double escaping (which as expected didn't work either) The regex should work fine I think I might be using the wrong operation?


Solution

  • Group the \\n, and then apply the + quantifier.

    (?:\\n)+
    
    \*\*Suggested by \<\@(.*?)\> \(ID\: (.*?)\)\*\*(?:\\n)+(.*)$