如何用JavaScript的string.match提取特定前缀后的目标内容?
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

