1

I want to replace text "1\n2" ("1" new line and "2")with for example "abcd". I've been searching a lot for solution but I can't find.

Below is my code

String REGEX = "1\n2";
Pattern p = Pattern.compile(REGEX, Pattern.DOTALL);
Matcher m = p.matcher(text);
String newText = m.replaceAll("abcd");

[EDIT] I'd like to add that text variable is read from file:

String text = new Scanner(new File("...")).useDelimiter("\\A").next();
3
  • 3
    You should escape the \. Commented Sep 30, 2013 at 12:39
  • Not working. When it's tabulator "1\t2" or "1\\t2" it works. Commented Sep 30, 2013 at 12:45
  • @user1411881 can you please paste the string which you are trying to modify ?? Commented Sep 30, 2013 at 13:02

3 Answers 3

4

Try to change your regex to

String REGEX = "1\\n2";

So it escapes the \n

Example:

public static void main(String[] args) {
    String REGEX = "1\n2";
    Pattern p = Pattern.compile(REGEX, Pattern.DOTALL);
    Matcher m = p.matcher("test1\n2test");
    String newText = m.replaceAll("abcd");
    System.out.println(newText);
}

O/P:

testabcdtest

Or even simply

String newText = "test1\n2test".replaceAll("1\n2", "abcd");

O/P

testabcdtest
Sign up to request clarification or add additional context in comments.

Comments

1

Why use a regex for this? Just use

String newText = text.replace("1\n2", "abcd");

1 Comment

Then your text doesn't contain "1\n2". Maybe it contains "1\r\n2"?
0

try this

String str="Your String"
str=str.replace("1\n2","abc");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.