Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式:查找以*或结尾的字符串?_Python_Regex - Fatal编程技术网

Python 正则表达式:查找以*或结尾的字符串?

Python 正则表达式:查找以*或结尾的字符串?,python,regex,Python,Regex,我试图找到一个正则表达式,它匹配以*或(独占-不是同时两个)+结尾的单词,并为以开头的字符串找到另一个正则表达式 以下是我尝试过的: import re txt = "~The ?rain in+ spain*" special = f"\\*+" special2 = f"\\~" x = re.search(f"\w*{special}\b", txt) #to find in+ and spain* x2

我试图找到一个正则表达式,它匹配以
*
或(独占-不是同时两个)
+
结尾的单词,并为以开头的字符串找到另一个正则表达式

以下是我尝试过的:

import re


txt = "~The ?rain in+ spain*"
special = f"\\*+"
special2 = f"\\~"
x = re.search(f"\w*{special}\b", txt) #to find in+ and spain*
x2 = re.search(f"^{special2}\w", txt) #to find ~The

print(x.string, x.group(), x.span() )
print(x2.string, x2.group(), x2.span() )

你可以试试这个



这些正则表达式查找文本
{special}
{special2}
,因为您没有使用f字符串。@JohnGordon用f替换了r并尝试了它,结果无效。。。我编辑了这篇文章。感谢您的建议:)在显示的代码中,重要的r字串没有被f字串替换。@MichaelButscher,很抱歉,我只编辑了2行而不是4行,但在我尝试的代码中,我为4行设置了f字串。请删除并粘贴您的实际代码,而不是用错误重新键入代码。您可以将其缩短为
~\w+\w+[+*]
import re

re.findall("~\w+|\w+(?:\+|\*)", text)
['~The', 'in+', 'spain*']