I am working on adding search / replace functionality to an android application.
I would like the user to be able to search and replace using regular expressions. The search functionality works correctly, however a newline character in the replacement string \n
is interpreted as a literal 'n'.
Here is what my code is doing:
Pattern.compile(search.getText().toString()).matcher(text).replaceAll(replace.getText().toString())
Given
- text is a
CharSequence
with contentsA \n\n\nB
(note the trailing space after 'A') search
being a textbox with the contents\s+\n
replace
being a text box with contents\n
.
I expect the result of the code above to be text = A\n\n\nB
(trailing spaces removed).
Instead the result is text = An\n\nB
. i.e. the \n
in the replace
text box is interpreted as a literal 'n'.
I would like to know what I can do in order to read the contents of replace
, such that the \n
is interpreted as a newline.
Note that I can achieve the desired result in the example by capturing the newline like with search
= \s+(\n)
and replace
= $1. This is not, however, the issue.
For the purposes of this discussion I am only considering Unix line endings.
Edit:
using replace
contents = \\n
results in a literal '\n' being inserted.
i.e.
A
B
is transformed to
A\n
B