Java: regex for highlighting:% j or% f

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

XYZ:% J Num:% f

becomes

XYZ: 12 Num: 34

+3
source share
4 answers

A simple way would be:

"XYZ: %J Num: %f".replace("%J", "12").replace("%f", "34");
+3
source
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, this may not be exactly the “easy way”, but it works.

+1
source

, , %J %, %J . .

XYZ: %J Num: %f. %%Just like I told you%%

XYZ: 12 Num: 34. %Just like I told you%

, . , - , .

+1
source

Maybe you really want to use the class java.util.Formatteror its wrapper methods everywhere in the library?

"XYZ: %Y Num: %f".format(new Date(), 30)

must give "XYZ: 2011 Num: 30.000000". Hmm, it doesn't seem like you want this, though ...

+1
source

Source: https://habr.com/ru/post/1791755/


All Articles