Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package exercise;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class BackReferences {
- public static void main(String[] args) {
- String input = "One:two:three:four";
- String regexe = "(\\w+):(\\w+):(\\w+):(\\w+)"; // pattern to be matched
- String replacement = "$4-$3-$2-$1"; // replacement pattern with back references
- // Step 1: Allocate a Pattern object to compile a regexe
- Pattern pattern = Pattern.compile(regexe);
- // Step 2: Allocate a Matcher object from the Pattern, and provide the input
- Matcher matcher = pattern.matcher(input);
- // Step 3: Perform the matching and process the matching result
- String output = matcher.replaceAll(replacement); // all matches
- //String output = matcher.replaceFirst(replacement); // first match only
- System.out.println(output);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement