Java中替换SVG字符串fill属性值的实现求助
Hey there! Let's fix that SVG fill color replacement problem you're working on. You need to swap out every fill="#FFFFFF" in your SVG content with a user-provided color code—here are a couple of solid approaches to get this done right.
Quick and Simple String Replacement
If you're confident your SVG consistently uses the exact format fill="#FFFFFF" (no extra spaces between fill, =, and the value), a straightforward replace() call will do the trick. Just concatenate the user's input with the # symbol and plug it into the replacement:
// Assume this is the color the user inputs (e.g., "ff0000") String userColorInput = "ff0000"; // Replace all instances of fill="#FFFFFF" with the user's color String updatedSvgContent = content.replace("fill=\"#FFFFFF\"", "fill=\"#" + userColorInput + "\"");
Robust Regex Replacement (Recommended)
SVG files sometimes have minor formatting variations—like spaces between fill and =, or even single quotes instead of double quotes. For these cases, using regular expressions will ensure you catch all valid instances of the fill property:
Handling Spaces in the Fill Attribute
This regex matches fill="#FFFFFF" even if there are spaces around the equals sign:
import java.util.regex.Matcher; import java.util.regex.Pattern; String userColorInput = "ff0000"; // Regex pattern to match fill="#FFFFFF" with optional spaces Pattern fillPattern = Pattern.compile("fill\\s*=\\s*\"#FFFFFF\""); Matcher matcher = fillPattern.matcher(content); // Replace all matches with the user's color String updatedSvgContent = matcher.replaceAll("fill=\"#" + userColorInput + "\"");
Supporting Both Single and Double Quotes
If your SVG might use single quotes (fill='#FFFFFF'), adjust the regex to handle both quote types while preserving the original quote style:
import java.util.regex.Matcher; import java.util.regex.Pattern; String userColorInput = "ff0000"; // Regex to match fill with either single or double quotes Pattern fillPattern = Pattern.compile("fill\\s*=\\s*(['\"])#FFFFFF\\1"); Matcher matcher = fillPattern.matcher(content); // Replace while keeping the original quote type String updatedSvgContent = matcher.replaceAll("fill=$1#" + userColorInput + "$1");
Why This Works
- The simple
replace()is great for controlled, consistent SVG formats. - Regex handles edge cases like whitespace or alternative quote styles, making your code more resilient to variations in SVG structure.
Just pick the approach that fits your specific use case, and you'll have that fill color swapped out in no time!
内容的提问来源于stack exchange,提问作者Swarnika Gupta

