Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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,我正在学习Python正则表达式(re)来分析twitter文本 假设我有下面这样的twitter文本,我只想从txt中准确提取“3/10”。 在本例中,Python返回空列表[] txt = "my mood is low 3/10. 05/01/2021 Tuesday" re.findall('^\d+\/\d{2}$', txt) 我的代码有什么问题?删除^和$ re.findall(r'\b\d+/\d{2}\b', txt) 不必使用锚来匹配整行,您可以使用负

我正在学习Python正则表达式(re)来分析twitter文本

假设我有下面这样的twitter文本,我只想从txt中准确提取“3/10”。
在本例中,Python返回空列表[]

txt = "my mood is low 3/10. 05/01/2021 Tuesday"
re.findall('^\d+\/\d{2}$', txt)

我的代码有什么问题?

删除
^
$

re.findall(r'\b\d+/\d{2}\b', txt)

不必使用锚来匹配整行,您可以使用负环行符在左侧断言空白边界,而不是在右侧断言仅匹配
3/10

(?<!\S)\d+\/\d{2}(?!/)

^
(插入符号)匹配字符串的开头,在多行模式下,也会在每个换行后立即匹配

$
匹配字符串的结尾或字符串结尾处的换行符之前,在多行模式下也匹配换行符之前。foo同时匹配'foo'和'foobar',而正则表达式foo$只匹配'foo'。更有趣的是,在'foo1\nfoo2\n'中搜索foo.$通常与'foo2'匹配,但在多行模式下搜索'foo1';在“foo\n”中搜索单个$将找到两个(空)匹配项:一个在换行符之前,另一个在字符串末尾


在你的例子中,情况并非如此。您需要使用更高级的零长度断言。

或使用
(?错误是
^
$
。它们标记行或字符串的开始和结束,并且您的正则表达式只匹配整行。
import re
txt = "my mood is low 3/10. 05/01/2021 Tuesday"
print(re.findall('(?<!\S)\d+\/\d{2}(?!/)', txt))
['3/10']