[英]Why does this Java regex fail?
In my Java code, I would like to match strings such as: 在我的Java代码中,我想匹配以下字符串:
1m
112m
10million
9Million
I also want to match stuff like "100k". 我还想匹配“ 100k”之类的东西。 The following works for the "k" but not for the "m".
以下内容适用于“ k”,不适用于“ 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
. 您的代码仅适用于100k,34m等,因为
match()
需要匹配整个字符串以返回true
。 So you can try with: 因此,您可以尝试:
moneyExp.matches("\\b[-+]?\\d+[kK](\\w+)+?\\b"); // for k
moneyExp.matches("\\b[-+]?\\d+[mM](\\w)+?\\b"); // for m
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.