what is the Java equivalent of sscanf for parsing values from a string using a known pattern?

后端 未结 8 863
梦如初夏
梦如初夏 2020-11-27 06:01

So I come from a C background (originally originally, though I haven\'t used that language for almost 5 years) and I\'m trying to parse some values from a string in Java. In

8条回答
  •  囚心锁ツ
    2020-11-27 06:40

    The problem is Java hasn't out parameters (or passing by reference) as C or C#.

    But there is a better way (and more solid). Use regular expressions:

    Pattern p = Pattern.compile("(\\d+)-(\\p{Alpha}+)-(\\d+) (\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)")
    Matcher m = p.matcher("17-MAR-11 15.52.25.000000000");
    day = m.group(1);
    month= m.group(2);
    ....
    

    Of course C code is more concise, but this technique has one profit: Patterns specifies format more precise than '%s' and '%d'. So you can use \d{2} to specify that day MUST be compose of exactly 2 digits.

提交回复
热议问题