I have a string like
“The brown fox @jumped@ over the @fence@”
, and I wish to replace all substrings between two '@' by ‘kicked‘ i.e. the final output should be :
“The brown fox kicked over the kicked”
I wrote the following but can’t figure out the mistake :
string.replaceAll("^@.*@$", "kicked");
You should not use anchor elements
^and$. They mean the beginning and the end of the entire input, not the beginning and the ending of the word. You should also replace the dot.with[^@](meaning “anything but@“) to make your expression more efficient.If you would like to avoid replacing tagged elements inside a word, e.g. if you want to preserve
he@ll@oas is, rather than making ithekikkedo, you can put in markers of word boundaries\bon both ends of the expression: