正则表达式需求:匹配含description字段的多属性文本内容
Hey there! Let's figure out how to extract those Attribute blocks that have a description field, keeping just the attribute header and the description itself. Here's a straightforward solution:
Regex Solution
First, here's the regular expression you can use:
(\[Attribute [^\]]+\]).*?(description=[^\[]+)
Breakdown of the regex:
(\[Attribute [^\]]+\]): This captures the full attribute header (like[Attribute Person]). The[^\]]+part matches any characters except the closing square bracket, so it works even if your attribute name has spaces or special characters (as long as it doesn't include])..*?: The non-greedy wildcard matches any characters in between the header and thedescriptionfield—this ensures we don't accidentally grab content from the next attribute block.(description=[^\[]+): This captures the entiredescriptionfield, stopping right before the next[(which signals the start of another attribute block).
Example Usage (JavaScript)
Here's how you'd implement this to get your desired output:
const inputText = "[Attribute Person] name=John description=This is a person age=16 [Attribute Things] name=Pencil description=This is an object [Attribute Something] name=John [Attribute Animal] name=Tom description=Just a regular cat age=2"; const regexPattern = /(\[Attribute [^\]]+\]).*?(description=[^\[]+)/g; const extractedResults = []; let match; while ((match = regexPattern.exec(inputText)) !== null) { // Combine the captured header and description extractedResults.push(`${match[1]} ${match[2]}`); } console.log(extractedResults);
Output:
[ "[Attribute Person] description=This is a person", "[Attribute Things] description=This is an object", "[Attribute Animal] description=Just a regular cat" ]
This regex will skip any attribute blocks that don't have a description field (like [Attribute Something] in your input), which is exactly what you need.
内容的提问来源于stack exchange,提问作者rredondo
相关产品推荐
相关产品推荐

