开发者

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

开发者 https://www.devze.com 2023-02-10 08:08 出处:网络
Is there an easy way to strip out something like %j or %f out of a string and replace it with an int?like:

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开发者_如何学Python Num: %f

becomes

XYZ: 12 Num: 34


A simple way would be:

"XYZ: %J Num: %f".replace("%J", "12").replace("%f", "34");


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.


If you want to do this reliably you should also take into consideration that %J might be prefixed with a % character, in which case %J should not be replaced. E.g.

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

which should then print as

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

So I do not think regular expressions can be used for this. You need to keep track of states, something simple like outlined in my answer here.


Maybe you in fact want to use the java.util.Formatter class or it's wrapper methods everywhere in the library?

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

should give "XYZ: 2011 Num: 30.000000". Hmm, does not look like you want this, though ...

0

精彩评论

暂无评论...
验证码 换一张
取 消