There's a bug at this pattern "^(.|#)?([\w-]+)([(.?)])?([:]{1,2}(.?))?\s*{([\s\S]*?)?}":
input[type="text"][placeholder="Search..."] {
}
What I want (from attributes) to be separated groups:
type="text"
placeholder="Search..."
Instead, I've got this matched:
type="text"][placeholder="Search..."
I want it to extract attributes no matter how much we add
Assistant
The issue with your current regex pattern lies in how it handles the attribute selectors within the square brackets []. Specifically, the part (\[(.*?)\])? is capturing everything from the first [ to the last ], which causes multiple attributes to be grouped together instead of being captured separately.
To resolve this, you need to adjust the regex so that each attribute inside [] is captured individually. Here's how you can modify your regex pattern:
^(\.|#)?: Captures a . (class) or # (ID) at the beginning, if present.
Element Name
([\w-]+): Captures the element/tag name (e.g., input).
Attributes
((\[[^]]+\])*)?:
\[[^]]+\]: Matches a single attribute selector, ensuring it doesn't consume multiple [].
(?:\[[^]]+\])*: The * allows for multiple attribute selectors.
The outer parentheses capture all attribute selectors as a single group, which you can further process to extract individual attributes.
Pseudo-classes/elements
([:]{1,2}(.*?))?: Captures pseudo-classes (:) or pseudo-elements (::), if any.
Declaration Block
\s*\{([\s\S]*?)?\}: Captures the CSS declaration block { ... }.
Extracting Individual Attributes
While the modified regex captures all attribute selectors together, you'll need an additional step to extract each attribute separately. Here's how you can do it:
First Regex Match: Use the modified regex to capture the entire selector and the attributes block.
Second Regex for Attributes: Apply another regex to the captured attributes block to extract each attribute individually.
regex
\[([\w-]+)="([^"]+)"\]
Explanation:
\[ and \]: Match the literal square brackets.
([\w-]+): Captures the attribute name.
="([^"]+)": Captures the attribute value inside double quotes.
Example Implementation
Here's an example in JavaScript demonstrating how to achieve this: