mydew
mydew

Reputation: 57

Java replaceAll with new lines in regex

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();

Upvotes: 1

Views: 226

Answers (3)

Suresh Atta
Suresh Atta

Reputation: 121998

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

Upvotes: 4

Rijo Joseph
Rijo Joseph

Reputation: 1405

try this

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

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691635

Why use a regex for this? Just use

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

Upvotes: 1

Related Questions