2

How can i split 100.26kg to System.out.println as

100.26
kg

I tried doing by using ("\d+") but was not successful.

String[] num = myTextCount.split("\\d+");

The 100.26kg may vary according to user input. It could be 100.26kg, 100g, 100 pounds or 100litre. If there is any way to split the number and alphabet, it will be very helpful

1
  • If it has a fixed format of #kg where # is any number, don't use regex. Commented Nov 24, 2013 at 8:54

6 Answers 6

1

myTextCount.split("[\\.\\d]+") will give you [, kg] which contain the second part, and then use #indexOf() to find the first part.

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

Comments

1

Try look-around regex,

  String[] num = myTextCount.split("(?<=\\d)(?=[a-z])|(?<=[a-z])(?=\\d)");

If you want to split case-insensitive with number than use (?i)

 String[] num = myTextCount.split("(?i)(?<=\\d)(?=[a-z])|(?<=[a-z])(?=\\d)");

1 Comment

kg is not fixed format. It can be pounds, gallon, litre and etc. That's why i need to split the integer and the string
0
import java.util.Scanner;

public class Sample {
    public static void main(String[] args) {
        String inputs[] = { "100.26kg", "100g", "100 pounds", "100litre"};

        String weight, unit;

        for(String input : inputs){
            Scanner scan = new Scanner(input);
            weight = scan.findInLine("\\d+(\\.\\d+)?");
            unit = scan.next();//scan.next("\\w+");

            System.out.println(weight);
            System.out.println(unit);
        }
    }
}

Comments

0

Do not use Split, just use the String.IndexOf() function to deal with it.

Comments

0
Matcher m = Pattern.compile("^([0-9.]+)\\s*([a-zA-Z]+)$").matcher("");
String inputs[] = {"100.26kg", "1 pound", "98gallons" };

for(String input: inputs)
{
    if ( m.reset(input).find() )
    {
        System.out.printf("amount=[%s] unit=[%s]\n", m.group(1), m.group(2) );
    }
}

yields:

amount=[100.26] unit=[kg]
amount=[1] unit=[pound]
amount=[98] unit=[gallons]

Comments

-1

Try this:

private static final Pattern VALID_PATTERN = Pattern.compile("[0-9]+|[A-Z]+");

private List<String> parse(String toParse) {
    List<String> chunks = new LinkedList<String>();
    Matcher matcher = VALID_PATTERN.matcher(toParse);
    while (matcher.find()) {
        chunks.add( matcher.group() );
    }
    return chunks;
}

This solution is quite modular as well.

1 Comment

it doesn't work for . values i.e 23.42 also for lower case characters

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.