正则表达式从列表中过滤日期

发布于 2025-01-18 12:07:59 字数 319 浏览 1 评论 0原文

我有一个如下所示的列表:

['','2022-03-31', 'euss', 'projects','2021-03-31']

我想编写一个正则表达式,以便从列表中删除所有其他项目,只保留那些具有日期格式的项目。例如,2022 年 3 月 31 日和 2021 年 3 月 31 日。

我尝试了这个,但当我打印列表时,它似乎没有什么区别:

my_list = [re.sub(r"(\d+)/(\d+)/(\d+)",r"\3-\1-\2",i) for i in list(my_list) ]

I have a list that looks like this:

['','2022-03-31', 'euss', 'projects','2021-03-31']

I want to write a regular expression such that I delete all other items from the list and only keep those that have a date format. For example, 2022-03-31 and 2021-03-31.

I tried this but it doesn't seem to make a difference when I print my list out:

my_list = [re.sub(r"(\d+)/(\d+)/(\d+)",r"\3-\1-\2",i) for i in list(my_list) ]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萧瑟寒风 2025-01-25 12:07:59

您可以首先检查正则表达式是否与字符串匹配:

result = []
rx = re.compile(r'(\d+)-(\d+)-(\d+)')
for i in my_list:
    if rx.search(i):                          # Check if the regex matches the string
        result.append(rx.sub(r"\3-\1-\2", i)) # Add modified string to resulting list

请参阅 Python 演示
输出:

['31-2022-03', '31-2021-03']

您可以将其写为:

rx = re.compile(r'(\d+)-(\d+)-(\d+)')
my_list = [rx.sub(r"\3-\1-\2", i) for i in my_list if rx.search(i)]

You can first check if there regex matches the string:

result = []
rx = re.compile(r'(\d+)-(\d+)-(\d+)')
for i in my_list:
    if rx.search(i):                          # Check if the regex matches the string
        result.append(rx.sub(r"\3-\1-\2", i)) # Add modified string to resulting list

See the Python demo.
Output:

['31-2022-03', '31-2021-03']

You may write it as:

rx = re.compile(r'(\d+)-(\d+)-(\d+)')
my_list = [rx.sub(r"\3-\1-\2", i) for i in my_list if rx.search(i)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文