Question

Sample input string : Customer ${/xml:Name} has Ordered Product ${/xml:product} of ${/xml:unit} units.

i able to find get strings that match ${ ...... } using "\\$\\{.*?\\}"

I resolve the value for string from xml and now i have to replace the value back in input string.

i am using this method,

Pattern MY_PATTERN = Pattern.compile("\\$\\{.*?\\}");
Matcher m = MY_PATTERN.matcher(inputstring);
while (m.find()) {
String s = m.group(0); // s is ${/xml:Name}

// escaping wild characters
s = s.replaceAll("${", "\\$\\{");  // s is \$\{/xml:Name}
s = s.replaceAll("}", "\\}"); // s is  \$\{/xml:Name\}

Pattern inner_pattern = Pattern.compile(s);
Matcher m1 = inner_pattern.matcher(inputstring);
name = m1.replaceAll(xPathValues.get(s));
}

but i get error at s = s.replaceAll("${", "\\$\\{"); i get Pattern Syntax Exception

enter image description here

Was it helpful?

Solution 2

Instead of:

s = s.replaceAll("${", "\\$\\{");  // s is \$\{/xml:Name}
s = s.replaceAll("}", "\\}"); // s is  \$\{/xml:Name\}

You can use it without regex method String#replace(string):

s = s.replace("${", "\\$\\{").replace("}", "\\}"); // s is \$\{/xml:Name\}

OTHER TIPS

You must escape the { too, try $\\{

It's because you could have a regexp likea{1,4} means to match a,aa,aaa,aaaa so a times 1 to 4, java tries to interpret your regexp like this, therefore try escaping the {

Yes, you must escape the {, but I would rather capture what's inside the braces:

Pattern MY_PATTERN = Pattern.compile("\\$\\{/xml:(.*?)\\}");
Matcher m = MY_PATTERN.matcher(inputstring);
while (m.find()) {
    name = m.group(1); // s is Name
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top