Advertisement
ivanov_ivan

BackReferences

Feb 4th, 2017
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1. package exercise;
  2.  
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5.  
  6. public class BackReferences {
  7.     public static void main(String[] args) {
  8.         String input = "One:two:three:four";
  9.         String regexe = "(\\w+):(\\w+):(\\w+):(\\w+)"; // pattern to be matched
  10.         String replacement = "$4-$3-$2-$1";    // replacement pattern with back references
  11.  
  12.         // Step 1: Allocate a Pattern object to compile a regexe
  13.         Pattern pattern = Pattern.compile(regexe);
  14.  
  15.         // Step 2: Allocate a Matcher object from the Pattern, and provide the input
  16.         Matcher matcher = pattern.matcher(input);
  17.  
  18.         // Step 3: Perform the matching and process the matching result
  19.         String output = matcher.replaceAll(replacement);     // all matches
  20.         //String output = matcher.replaceFirst(replacement); // first match only
  21.         System.out.println(output);
  22.     }
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement