在C#中为所有CSS选择器添加#ID前缀的实现求助
Got it, I’ve been in similar spots where I needed to scope CSS to a specific container without rewriting the whole stylesheet. Here’s a straightforward way to prepend your target ID prefix to each selector in your CSS string using C#:
Step-by-Step Solution
We’ll use regular expressions to match each CSS selector line and insert the ID prefix. This works perfectly for your example of element selectors (body, header, etc.), and can be adjusted if you have more complex selectors later.
Example Code
using System.Text.RegularExpressions; // Your original CSS string string originalCss = @"body { color: white; background-color: #aaaaaa } header { color: blue; background-color: #bbbbbb } main { color: red; background-color: #cccccc } footer { color: green; background-color: #dddddd }"; // Define your target ID prefix string idPrefix = "#someID"; // Use regex to prepend the prefix to each selector string modifiedCss = Regex.Replace( originalCss, @"(^\s*)([\w-]+)(\s*{)", $"$1{idPrefix} $2$3", RegexOptions.Multiline );
What This Does
- The
RegexOptions.Multilineflag lets the^character match the start of every line (not just the start of the entire string). - The regex breaks down each line into three groups:
(^\s*): Captures any leading whitespace before the selector (so we preserve original formatting).([\w-]+): Matches the selector itself (works for element names, class names, and IDs with hyphens).(\s*{): Captures whitespace before the opening brace and the brace itself.
- The replacement string inserts your ID prefix between the leading whitespace and the selector, keeping everything formatted as it was.
Result
The modified CSS will look exactly like what you need:
#someID body { color: white; background-color: #aaaaaa } #someID header { color: blue; background-color: #bbbbbb } #someID main { color: red; background-color: #cccccc } #someID footer { color: green; background-color: #dddddd }
Notes for More Complex CSS
If your stylesheet includes combinators (like div p), nested selectors, or pseudo-classes, you can tweak the regex to handle those. For example, to match selectors that might have spaces or other characters, you could use a more flexible pattern like @"(^\s*)([^}]+?)(\s*{)" — just be aware this might need additional refinement based on your specific CSS structure.
内容的提问来源于stack exchange,提问作者Carlos Miranda

