Backslashes in regular expressions - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Description

Backslashes in regular expressions

Demo Code

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] argv) {
    String rep = "a\\\\b";
    String input = "> XYZ <=> ABC <";
    Pattern pattern = Pattern.compile("ABC|XYZ");
    Matcher matcher = pattern.matcher(input);

    System.out.println(matcher.replaceFirst(rep));
    System.out.println(matcher.replaceAll(rep));

    rep = "\\\\r\\\\n";
    input = "line 1\nline 2\nline 3\n";
    pattern = Pattern.compile("\\n");
    matcher = pattern.matcher(input);/*from  www.java 2s  .co m*/

    System.out.println("");
    System.out.println("Before:");
    System.out.println(input);

    System.out.println("After (dos-ified, escaped):");
    System.out.println(matcher.replaceAll(rep));
  }
}

Result


Related Tutorials