# 正则表达式匹配 (""或任意非数字字符)("0"或"") + today.month + "月" + ("0"或"") + today.day + "日"
# (?<![0-9]) 与 \D 与 \d的区别
UserWarning: This pattern is interpreted as a regular expression, and has match groups. To actually get the groups, use str.extract.
df_today = df_dir[df_dir.iloc[:, 0].str.contains(pattern, regex=True)]
import datetime
today = datetime.date.today()
# 正则表达式匹配 (""或任意非数字字符)("0"或"") + today.month + "月" + ("0"或"") + today.day + "日"
pattern = r"(\D?0?{})月(0?{})日".format(today.month, today.day)
这是一个警告,表示你正在使用的正则表达式包含匹配组。在Pandas的str.contains()
函数中,正则表达式的匹配组不会被单独提取出来。如果你想要获取这些匹配组的内容,你应该使用str.extract()
函数,而不是str.contains()
。
这是一个例子来说明如何使用str.extract()
:
df_today = df_dir[df_dir.iloc[:, 0].str.extract(pattern, expand=False).notna()]
在这个例子中,str.extract()
函数会返回一个DataFrame,其中包含了匹配到的组。expand=False
参数表示如果只有一个匹配组,那么返回一个Series而不是DataFrame。notna()
函数用于选择非空的行,即那些匹配到正则表达式的行。
请注意,如果你的正则表达式有多个匹配组,那么str.extract()
会返回一个DataFrame,每一列对应一个匹配组。在这种情况下,你可能需要使用any(axis=1)
来选择至少匹配到一个组的行。
pandas contains 与 extract 的区别 正如 re.search 与 findall 的区别
pandas startwith 正如 re.match 从头匹配
匹配尾巴 pandas endwith 而re则使用正则表达式符号
在正则表达式中,如果你想要匹配字符串的尾部,你可以使用$
符号⁵⁶。$
符号表示匹配行或字符串的结束⁵⁶。例如,如果你想要匹配所有以.txt
结尾的字符串,你可以使用正则表达式.*\.txt$
²。
这里是一个例子²:
import re
# 匹配以数字结尾的数据
match_obj = re.match(".*\\d$", "hello5")
if match_obj:
# 获取匹配结果
print(match_obj.group())
else:
print("匹配失败")
在这个例子中,.*\\d$
是一个正则表达式,它匹配所有以数字结尾的字符串²。如果字符串"hello5"以数字结尾,match_obj.group()
将返回整个匹配的字符串²。
希望这个解释对你有所帮助!源: 与必应的对话, 2023/12/2
(1) 正则表达式 – 语法 | 菜鸟教程. https://www.runoob.com/regexp/regexp-syntax.html.
(2) 正则表达式结尾匹配|极客教程. https://geek-docs.com/regexp/regexp-tutorials/63_the_end_of_the_regular_expression_matches.html.
(3) [正则表达式] 匹配开头和结尾 - CSDN博客. https://blog.csdn.net/weixin_42482896/article/details/108086467.
(4) 正则表达式如何获得最后一个匹配? - 知乎. https://www.zhihu.com/question/23258550.
(5) 正则表达式 – 语法 | 菜鸟教程. https://bing.com/search?q=正则表达式+尾部.
(6) 如何在Python中使用正则表达式匹配字符串末尾?|极客教程. https://geek-docs.com/python/python-ask-answer/t_how-to-match-at-the-end-of-string-in-python-using-regular-expression.html.
(7) undefined. http://www.w3.org/1999/xhtml.