Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Regular expression to strip out: %j or %f

Tags:

java

Is there an easy way to strip out something like %j or %f out of a string and replace it with an int? like:

XYZ: %J Num: %f

becomes

XYZ: 12 Num: 34

like image 673
Snow_Mac Avatar asked Mar 09 '26 04:03

Snow_Mac


2 Answers

A simple way would be:

"XYZ: %J Num: %f".replace("%J", "12").replace("%f", "34");
like image 129
Costi Ciudatu Avatar answered Mar 11 '26 18:03

Costi Ciudatu


import java.util.Enumeration;
import java.util.Hashtable;

public class BasicReplace {

    public static void main(String[] args) {
        Hashtable<String, Integer> values = new Hashtable<String, Integer>();
       values.put("%J", 3);
       values.put("%F", 5);
       values.put("%E", 7);
        String inputStr = "XYZ: %J ABC: %F";
        String currentKey;
        Enumeration<String> enume = values.keys();
        while(enume.hasMoreElements()){
            currentKey = enume.nextElement();
            inputStr = inputStr.replaceAll(currentKey, String.valueOf(values.get(currentKey)));
        }
        System.out.println(inputStr);
        System.out.println("XYZ: %J Num: %f".replace("%J", "12").replace("%f", "34"));
    }
}

TUNDUN ! :D
Well, it might not exactly be "an easy way", but it works.

like image 23
POSIX_ME_HARDER Avatar answered Mar 11 '26 17:03

POSIX_ME_HARDER



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!