Tokuchi Toua
Tokuchi Toua

Reputation: 175

split method java

I would like to know the regex for removing the period from a string without affecting the decimal number and then store them as separate tokens

str = "..A 546.88 end."

in the above string value I just need only the values "546.88", "A", "end" and store them into an array

thanks for help

Upvotes: 2

Views: 675

Answers (2)

Ina
Ina

Reputation: 4470

You seem to have two questions. The first is removing all periods which aren't part of a decimal number, which you can do by preserving the two groups from the following regex:

"(.*(\\D|^))\\.+((\\D|$).*)"

This regex is: Anything - Not digit or start of line - Period - Not digit or end of line - Anything

String s = "..A 546.88 .end.";
Pattern p = Pattern.compile("(.*(\\D|^))\\.+((\\D|$).*)");
Matcher m = p.matcher(s);
while(m.matches())
{
    s = m.group(1) + "" + m.group(3);
    System.out.println(s);
    m = p.matcher(s);
}

Gives

A 546.88 end

The second problem is getting the three values out of the remaining string, for which you can just use myString.split("\\s+") - which gives you the three values in an array.

String[] myArray = s.split("\\s+");

Upvotes: 2

David Kroukamp
David Kroukamp

Reputation: 36423

The most generic would be:

[0-9]+(\.[0-9][0-9]?)?

I created a small sample to do what you ask in your comment:

what i want is an array containing "A", "546.88", "end" if it's possible

public class JavaApplication39 {

    static String str = "..A 546.88 end.";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Create a pattern to match breaks
        Pattern p = Pattern.compile("[0-9]+(\\.[0-9][0-9]?)?");
        // Split input with the pattern
        String[] result = p.split(str);
        Matcher m = p.matcher(str);
        ArrayList<String> strings = new ArrayList<>();

        while (m.find()) {//all those that match
            strings.add(m.group());
            //System.out.println(m.group());
        }

        for (int i = 0; i < result.length; i++) {//all those that dont match
            strings.add(result[i].replaceAll("\\.", "").trim());//strip '.' and ' '
            // System.out.println(result[i]);
        }
        //all contents in array
        for (Iterator<String> it = strings.iterator(); it.hasNext();) {
            String string = it.next();
            System.out.println(string);
        }
    }
}

Upvotes: 4

Related Questions