Question

I want to use replaceAll() for the following replacements:

#one# -> <element name="one">
#two# -> <element name="two">

and so on...

What regular expression do I need?

Here is a naive try:

replaceAll("#[\w]#", "<element name=\"[?1]\"");
// my hope is that I can remember a value somehow (`[\w]`) and use it for the substitution ([?1])
// which is, written like this, a nonsense
Was it helpful?

Solution

You need to use:

str = str.replaceAll("#(\\w+)#", "<element name=\"$1\">");
  • You need \\w+ OR [^#]+ to match more than 1 character
  • You need to put them in parentheses to make it a capturing group
  • You can use back-reference to this matched group by using $1 n replacement string
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top