7
投票
如果你想从Int中提取所有Float和String,你可以按照我的解决方案:
private ArrayList parseIntsAndFloats(String raw) {
ArrayList listBuffer = new ArrayList();
Pattern p = Pattern.compile("[0-9]*\\.?[0-9]+");
Matcher m = p.matcher(raw);
while (m.find()) {
listBuffer.add(m.group());
}
return listBuffer;
}
如果你想解析负值,你可以将[-]?添加到模式中,如下所示:
Pattern p = Pattern.compile("[-]?[0-9]*\\.?[0-9]+");
如果您还想将,设置为分隔符,则可以将,?添加到模式中,如下所示:
Pattern p = Pattern.compile("[-]?[0-9]*\\.?,?[0-9]+");
.
注意:对于这个工具,如果你正在尝试我的例子,请记得unescape(你只需要取下一个\)
3
投票
您可以尝试使用正则表达式匹配数字
\\d+\\.\\d+
这可能看起来像
Pattern p = Pattern.compile("\\d+\\.\\d+");
Matcher m = p.matcher("eXamPLestring>1.67>>ReSTOfString");
while (m.find()) {
Float.parseFloat(m.group());
}
2
投票
String s = "eXamPLestring>1.67>>ReSTOfString>>0.99>>ahgf>>.9>>>123>>>2323.12";
Pattern p = Pattern.compile("\\d*\\.\\d+");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(">> "+ m.group());
}
只提供花车
>> 1.67
>> 0.99
>> .9
>> 2323.12
2
投票
以下是如何在一行中完成的,
String f = input.replaceAll(".*?([\\d.]+).*", "$1");
如果你真的想要一个float,这里是你如何在一行中做到这一点:
float f = Float.parseFloat(input.replaceAll(".*?([\\d.]+).*", "$1")),
1
投票
你可以使用正则表达式\d*\.?,?\d*这适用于像1.0和1,0的浮点数
1
投票
看看这个link,他们还解释了构建这样一个正则表达式时需要记住的一些事项。
[-+]?[0-9]*\.?[0-9]+
示例代码:
String[] strings = new String[3];
strings[0] = "eXamPLestring>1.67>>ReSTOfString";
strings[1] = "eXamPLestring>0.57>>ReSTOfString";
strings[2] = "eXamPLestring>2547.758>>ReSTOfString";
Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+");
for (String string : strings)
{
Matcher matcher = pattern.matcher(string);
while(matcher.find()){
System.out.println("# float value: " + matcher.group());
}
}
输出:
# float value: 1.67
# float value: 0.57
# float value: 2547.758
1
投票
/**
* Extracts the first number out of a text.
* Works for 1.000,1 and also for 1,000.1 returning 1000.1 (1000 plus 1 decimal).
* When only a , or a . is used it is assumed as the float separator.
*
* @param sample The sample text.
*
* @return A float representation of the number.
*/
static public Float extractFloat(String sample) {
Pattern pattern = Pattern.compile("[\\d.,]+");
Matcher matcher = pattern.matcher(sample);
if (!matcher.find()) {
return null;
}
String floatStr = matcher.group();
if (floatStr.matches("\\d+,+\\d+")) {
floatStr = floatStr.replaceAll(",+", ".");
} else if (floatStr.matches("\\d+\\.+\\d+")) {
floatStr = floatStr.replaceAll("\\.\\.+", ".");
} else if (floatStr.matches("(\\d+\\.+)+\\d+(,+\\d+)?")) {
floatStr = floatStr.replaceAll("\\.+", "").replaceAll(",+", ".");
} else if (floatStr.matches("(\\d+,+)+\\d+(.+\\d+)?")) {
floatStr = floatStr.replaceAll(",", "").replaceAll("\\.\\.+", ".");
}
try {
return new Float(floatStr);
} catch (NumberFormatException ex) {
throw new AssertionError("Unexpected non float text: " + floatStr);
}
}