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

如何用JavaScript的string.match提取特定前缀后的目标内容?

Extracting Specific Content from Strings as Required

To solve this problem, we need to pull the quoted content only when it’s enclosed in square brackets right after specialPrefix: (with optional whitespace in between). If the content isn’t wrapped in brackets, we return an empty array as specified.

Approach

The key here is using a regular expression to detect the presence of square brackets following the prefix. When we find that pattern, we extract the content inside, split it into individual items, and clean up any extra whitespace or quotes. If no brackets are present, we immediately return an empty array.

Implementation in Python

Here’s a simple, effective solution using Python’s regex module:

import re

def extract_special_content(input_str):
    # Regex to match the prefix, optional whitespace, and bracketed content
    pattern = r'specialPrefix:\s*\[([^\]]+)\]'
    match = re.search(pattern, input_str)
    
    if match:
        # Grab the content inside the brackets
        inner_content = match.group(1)
        # Split into items, stripping quotes and extra spaces
        items = [item.strip().strip("'") for item in inner_content.split(',')]
        return items
    else:
        # No brackets found—return empty array
        return []

# Test with your input strings
input1 = "any string before specialPrefix: ['content1', 'content2'] and any other text after"
input2 = "any string before specialPrefix:['content1', 'content2'] and any other text after"
input3 = "any string before specialPrefix: 'content1', 'content2' and any other text after"

print(extract_special_content(input1))  # Output: ['content1', 'content2']
print(extract_special_content(input2))  # Output: ['content1', 'content2']
print(extract_special_content(input3))  # Output: []

Breakdown of the Solution

  • Regex Pattern: specialPrefix:\s*\[([^\]]+)\]
    • specialPrefix: matches the exact required prefix.
    • \s* accounts for any number of spaces (or none) between the prefix and opening bracket.
    • \[ targets the opening square bracket.
    • ([^\]]+) captures all characters until the closing bracket—this is our desired content.
    • \] matches the closing square bracket.
  • Content Processing: When a match is found, we split the captured text by commas, then strip surrounding whitespace and single quotes from each item to get clean values. If no match exists (like in input3), we return an empty array.

This solution handles the whitespace variations between input1 and input2 perfectly, and correctly ignores cases where the content isn’t bracketed like input3.

内容的提问来源于stack exchange,提问作者Lonli-Lokli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:10:08