从格式化字符串 Java、Groovy 中读取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12260849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:13:11  来源:igfitidea点击:

Read values from formatted string Java, Groovy

javastringgroovy

提问by kuceram

I'm wondering if there is any nice way how to read single attributes from formatted string in Groovy or even in Java.

我想知道是否有什么好的方法可以从 Groovy 甚至 Java 中的格式化字符串中读取单个属性。

I have a string containing some attributes separated by space. For example "2.1 20 Something true". The order is fixed and the "attribute type" is known (for the example first is Float, second is Integer, etc.). I need something similar to String.format() but other way round.

我有一个包含一些由空格分隔的属性的字符串。例如“2.1 20Something true”。顺序是固定的,并且“属性类型”是已知的(例如,第一个是浮点数,第二个是整数,等等)。我需要类似于 String.format() 但其他方式的东西。

I know that I can split the string manually and read the values, but this makes the code too complicated like this:

我知道我可以手动拆分字符串并读取值,但这会使代码变得过于复杂,如下所示:

String[] parsedText = "2.1 20 Something true".split(delimiter)

try {
   firstVal = new Float(parsedText[0])
}
catch (NumberFormatException e) {
   throw new RuntimeException("Bad data [0th position in data string], cannot read[{$parsedData[0]}], cannot convert to float")
}
...

Is there a better way? I'm pretty sure that at least in Groovy is:-)

有没有更好的办法?我很确定至少在 Groovy 中是:-)

Thanks!

谢谢!

回答by chm

The Java Scannerclass has a whole bunch of methods for grabbing and parsing the next part of a string, e.g. next(), nextInt(), nextDouble(), etc.

Java的扫描仪类有抓取和解析字符串的下一个部分,例如一整串的方法next()nextInt()nextDouble(),等。

The code looks like this:

代码如下所示:

String input = "2.1 20 Something true";
Scanner s = new Scanner(input);
float f = s.nextFloat();
int i = s.nextInt();
String str = s.next(); // next() doesn't parse, you automatically get a string
boolean b = s.nextBoolean();

Only thing to be wary of: next()and nextLine()both get you strings, but next()only gets you the string up to the next space. If you want your string components to have spaces in them you'll need to account for that.

唯一要提防的:next()nextLine()两个让你字符串,但next()只让你串到下一个空间。如果您希望字符串组件中有空格,则需要考虑到这一点。

回答by JJ Roman

Scanner class from java.util should do the job for you. While reading from input there is much more cases which you need to be taken into account.

java.util 中的 Scanner 类应该为您完成这项工作。在从输入中读取时,您需要考虑更多情况。

In your case you can call scanner methods in a row or use regexp to have "format string" explicitly defined and keep it tided in one place. In this way you will benefit by having validation at once.

在您的情况下,您可以连续调用扫描仪方法或使用正则表达式明确定义“格式字符串”并将其保持在一个位置。通过这种方式,您将受益于立即进行验证。

//calling methods in row
{
    Scanner sc = new Scanner("2.1 20 Something true");
    float f = sc.nextFloat();
    int i = sc.nextInt();
    String s = sc.nextLine();

    System.out.print(String.format("%s\t%.2f\t%x\n", s, f, i));

    sc.close();
}
//using regexp
{
    Scanner sc = new Scanner("2.1 20 Something true");
    sc.findInLine("(\d+[\.,]?\d*)\s(\d+)(\s.*)$");
    MatchResult result = sc.match();
    float f = Float.parseFloat(result.group(1));
    int i = Integer.parseInt(result.group(2));
    String s = result.group(3);

    System.out.print(String.format("%s\t%.2f\t%x\n", s, f, i));

    sc.close();
}

Scanner class has different constructors to use the class with objects of type: File, InputStream, Readable, ReadableByteChannel and as spotted in example with String.

Scanner 类具有不同的构造函数,可以将该类与以下类型的对象一起使用:File、InputStream、Readable、ReadableByteChannel 以及在 String 示例中发现的。

Be aware that this class is locale aware so it may behaves differently depends on system settings (some countries use coma instead point for floating point, etc ...). You can override locale settings.

请注意,此类是区域设置感知的,因此它的行为可能会因系统设置而异(某些国家/地区使用昏迷代替浮点数等......)。您可以覆盖区域设置。

Here is comprehensive reference: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

这里是综合参考:http: //docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html