简体   繁体   中英

Why does this Java regex fail?

In my Java code, I would like to match strings such as:

1m
112m
10million
9Million

I also want to match stuff like "100k". The following works for the "k" but not for the "m". Why is that?

if (moneyExp.matches("[-+]?\\d+[kK]")) {
    String modMoney = moneyExp.replaceAll("[^\\d.]", "");
    modMoney += "000";
    mw.hashX.remove("Amount");
    mw.doublePut("Amount", modMoney, 1);
    tagMap = mw.hashX;
} else if (money.matches("[-+]?\\d+[mM]")) {
    String modMoney = moneyExp.replaceAll("[^\\d.]", "");
    modMoney += "000000";
    mw.hashX.remove("Amount");
    mw.doublePut("Amount", modMoney, 1);
    tagMap = mw.hashX;
}

Your code works only with 100k, 34m etc. because the match() need to match whole string to return true . So you can try with:

moneyExp.matches("\\b[-+]?\\d+[kK](\\w+)+?\\b"); // for k
moneyExp.matches("\\b[-+]?\\d+[mM](\\w)+?\\b");  // for m

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM