5

let's say i have string like that:

eXamPLestring>1.67>>ReSTOfString

my task is to extract only 1.67 from string above.

I assume regex will be usefull, but i can't figure out how to write propper expression.

2

7 Answers 7

11

If you want to extract all Int's and Float's from a String, you can follow my solution:

private ArrayList<String> parseIntsAndFloats(String raw) {

    ArrayList<String> listBuffer = new ArrayList<String>();

    Pattern p = Pattern.compile("[0-9]*\\.?[0-9]+");

    Matcher m = p.matcher(raw);

    while (m.find()) {
        listBuffer.add(m.group());
    }

    return listBuffer;
}

If you want to parse also negative values you can add [-]? to the pattern like this:

    Pattern p = Pattern.compile("[-]?[0-9]*\\.?[0-9]+");

And if you also want to set , as a separator you can add ,? to the pattern like this:

    Pattern p = Pattern.compile("[-]?[0-9]*\\.?,?[0-9]+");

.

To test the patterns you can use this online tool: http://gskinner.com/RegExr/

Note: For this tool remember to unescape if you are trying my examples (you just need to take off one of the \)

Sign up to request clarification or add additional context in comments.

Comments

3

You could try matching the digits using a regular expression

\\d+\\.\\d+

This could look something like

Pattern p = Pattern.compile("\\d+\\.\\d+");
Matcher m = p.matcher("eXamPLestring>1.67>>ReSTOfString");
while (m.find()) {
    Float.parseFloat(m.group());
}

Comments

3

Here's how to do it in one line,

String f = input.replaceAll(".*?(-?[\\d.]+)?.*", "$1");

Which returns a blank String if there is no float found.

If you actually want a float, you can do it in one line:

float f = Float.parseFloat(input.replaceAll(".*?(-?[\\d.]+).*", "$1"));

but since a blank cannot be parsed as a float, you would have to do it in two steps - testing if the string is blank before parsing - if it's possible for there to be no float.

2 Comments

What if there is no number in the String at all? It just returns the original String instead of an empty String.
@FabZbi I modified the regex to return a blank if there's no float - I just added a ? after the capture group to make it optional.
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());
    }

Gives only floats

>> 1.67
>> 0.99
>> .9
>> 2323.12

Comments

1

You can use the regex \d*\.?,?\d* This will work for floats like 1.0 and 1,0

Comments

1

Have a look at this link, they also explain a few things that you need to keep in mind when building such a regex.

[-+]?[0-9]*\.?[0-9]+

example code:

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());
        }
    }

output:

# float value: 1.67
# float value: 0.57
# float value: 2547.758

Comments

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.