如何用Java的replaceAll结合正则替换指定XML标签间内容
Got it, let's work through how to swap out the content inside <Details> under the <Customer> tag using Java's replaceAll method. I'll start with a working code example, then break down the regex so you understand exactly what's happening.
Code Implementation
public class XmlContentReplace { public static void main(String[] args) { String abc = "<Message> <Details> hello </Details> </Message> <Customer> <Details> John </Details> </Customer> <Bank> <Details> BANK1 <Details> <Bank>"; // Perform the targeted replacement String updatedAbc = abc.replaceAll( "(?<=<Customer>\\s*<Details>\\s*).*?(?=\\s*</Details>\\s*</Customer>)", "Peter" ); System.out.println(updatedAbc); } }
Regex Breakdown
Let's unpack the regex to see why it preserves your XML structure while making the exact change you need:
(?<=<Customer>\\s*<Details>\\s*): This is a positive lookbehind that locks us right after the<Customer>tag (allowing any whitespace between<Customer>and<Details>) and the opening<Details>tag. It doesn't modify or consume these tags—just checks our position..*?: The non-greedy wildcard matches any character (except newlines) as few times as possible. This is key to avoiding accidental matches of content from other<Details>tags later in the string.(?=\\s*</Details>\\s*</Customer>): This is a positive lookahead that ensures we're positioned right before the closing</Details>tag (again, allowing whitespace) and closing</Customer>tag. Like the lookbehind, it leaves these tags untouched.
Expected Output
Running the code will generate exactly the string you're targeting:
String abc = "<Message> <Details> hello </Details> </Message> <Customer> <Details> Peter</Details> </Customer> <Bank> <Details> BANK1 <Details> <Bank>"
A Quick Caveat
While this regex works flawlessly for your specific simple XML structure, remember that regex isn't the best tool for complex XML (like nested tags or tags with attributes). For more robust XML manipulation, you'd want to use a dedicated parser like JDOM or DOM. But since you specifically requested replaceAll with regex, this solution fits your requirements perfectly.
内容的提问来源于stack exchange,提问作者Phalani Kumar

