You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用正则表达式从列表中抓取含listing关键词的元素

Solution: Filter List Elements Containing "listing" Using Regex

Got it, let's break down how to filter your list to get only the elements that include the "listing" keyword using Python's regex module.

Step 1: Import the Regex Module

First, we need to import re to work with regular expressions:

import re

Step 2: Define Your Original List

Let's start with the list you provided:

x = ['/category/Women-Dresses?size=0', '/brand/Free_People', '/closet/shopmyycloset', '/listing/559c0800568c896f6e019f2a/unlike', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a', None, '#', '#', '#', '#', '#', None, ]

Step 3: Create the Regex Pattern and Filter the List

We'll use a regex pattern to detect the presence of "listing" in each string, and also skip non-string elements (like None in your list):

# Compile a regex pattern to look for the "listing" substring
listing_pattern = re.compile(r'listing')

# Filter the list: keep only strings that contain "listing"
c = [item for item in x if isinstance(item, str) and listing_pattern.search(item)]

What This Does:

  • isinstance(item, str): Ensures we don't try to run regex checks on None or other non-string values (which would throw errors).
  • listing_pattern.search(item): Checks if the substring "listing" exists anywhere in the string. If it does, the element is kept in the new list c.

Result

When you run this code, c will be exactly the target list you want:

print(c)
# Output:
# ['/listing/559c0800568c896f6e019f2a/unlike', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a']

Optional: Strict Matching (If Needed)

If you want to only keep elements that start with /listing/ (instead of any string containing "listing"), you can adjust the regex pattern to:

listing_pattern = re.compile(r'^/listing/')

This ensures we only match URLs that begin with the /listing/ path segment, avoiding any accidental matches with "listing" in other parts of the string.

内容的提问来源于stack exchange,提问作者Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:05:33