How to parse a string to get a decimal number and a dotted word correctly?

How to distinguish the difference from finding the decimal number, but at the same time ignoring it, if it is a period?

For example, suppose Scanner

String s = "2015. 3.50 please";

When I use the function scanner.hasNextFloat(), how to ignore Hi.?

I only scan 1 line. I need to determine if a word is a string, integer or float. My end result should look something like this:

This is a String: 2015.
This is a float: 3.50
This is a String: please

But in my conditions, when I use it scanner.hasNextFloat();, it identifies 2015. as a float.

+1
source share
3 answers

Java . , , . -

String s = "Hi. 3.50 please";
Pattern p = Pattern.compile(".*(\\d+\\.\\d{2}).*");
Matcher m = p.matcher(s);
Float amt = null;
if (m.matches()) {
    amt = Float.parseFloat(m.group(1));
}
System.out.printf("Ammount: %.2f%n", amt);

Ammount: 3.50
+1

, java, javascript .

    String s = "Hi. 3.50 please";

    Scanner scanner = new Scanner(s);
    while (scanner.hasNext()){
        if (scanner.hasNextInt()){
            System.out.println("This is an int: " + scanner.next());
        } else if (scanner.hasNextFloat()){
            System.out.println("This is a float: " + scanner.next());
        } else {
            System.out.println("This is a String: " + scanner.next());
        }

    }

:

This is a String: Hi.
This is a float: 3.50
This is a String: please

, ?

0

You can use regex to match numbers

    String[] str = { " Hi, My age is 12", "I have 30$", "Eclipse version 4.2" };
    Pattern pattern = Pattern.compile(".*\\s+([0-9.]+).*");
    for (String string : str) {
        Matcher m = pattern.matcher(string);
        System.out.println("Count " + m.groupCount());
        while (m.find()) {
            System.out.print(m.group(1) + " ");
        }
        System.out.println();
    }

Output:

Count 1 12 Count 1 30 Count 1 4.2

If numbers can have power eor e, add [0-9.eE]String to the pattern

0
source

Source: https://habr.com/ru/post/1612655/


All Articles