PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

Replace

Replace all "Java 1.5" with Java "5.0"
 
package testexample;
import java.util.regex.*;

public class Testexample {
    
    public static void main(String[] args) {
        
        String text = "Before Java 1.5 was Java 1.4.2. " .
                                  "After Java 1.5 is Java 1.6";

        String regex = "\bJava 1\.5\b";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(text);
        
        String result = m.replaceAll("Java 5.0");
        System.out.println(result);
            // Before Java 5.0 was Java 1.4.2. 
            // After Java 5.0 is Java 1.6
    }
}
... 10 lines
 
Replace Or    (2/2)

Replace OR

Replace all "Java 1.5 (or 1.6)" with "Java 5.0 (or 6.0)". You can use replaceFirst to replace only the first match. Intances of $1 and $2, ... replaced by the text matched by capturing parentheses.
 
package testexample;

import java.util.regex.*;

public class Testexample {
    
    public static void main(String[] args) {
               
        String text = "Before Java 1.5 was Java 1.4.2." . 
                                 "After Java 1.5 is Java 1.6";

        String regex = "\bJava *1\.([56])\b";

        String result = Pattern.compile(regex).matcher(text).replaceAll("Java $1.0");

        System.out.println(result);
            // Before Java 5.0 was Java 1.4.2. After Java 5.0 is Java 6.0
    }
}
... 7 lines
 

Questions    
Split

        A B C D E F
🔔
1/2