在Python 3.11中捕获正则表达式中的数据

huangapple go评论75阅读模式
英文:

Capturing data in regex in python 3.11

问题

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

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:
在Python 3.11中捕获正则表达式中的数据

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?

英文:

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

\*\*Suggested by \&lt;\@(.*?)\&gt; \(ID\: (.*?)\)\*\*\\n+(.*)$

along with a template string:

**Suggested by &lt;@1234567890&gt; (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)
在Python 3.11中捕获正则表达式中的数据
however it can be skipped by replacing \n+ with \n\n

When trying to use this in python:

import re

user_input = &#39;**Suggested by &lt;@1234567890&gt; (ID: 1234567890)**\n\ntesting new idea&#39;
regex = re.compile(r&#39;\*\*Suggested by \&lt;\@(.*?)\&gt; \(ID\: (.*?)\)\*\*\\n+(.*$)&#39;)
content = re.search(regex, user_input)
print(content.group(1))
print(content.group(2))
print(content.group(3))

I'm getting this error
在Python 3.11中捕获正则表达式中的数据

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?

答案1

得分: 0

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

(?:\\n)+
\*\*由\&lt;\@(.*?)\&gt; \(ID\: (.*?)\)\*\*(?:\\n)+(.*)$
英文:

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

(?:\\n)+
\*\*Suggested by \&lt;\@(.*?)\&gt; \(ID\: (.*?)\)\*\*(?:\\n)+(.*)$

huangapple
  • 本文由 发表于 2023年6月12日 22:31:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76457670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定