Reputation: 31
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
Upvotes: 2
Views: 1576
Reputation: 40145
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);
}
}
}
Upvotes: 0
Reputation: 21971
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)");
Upvotes: 1
Reputation: 7257
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]
Upvotes: 0
Reputation: 11
Do not use Split
, just use the String.IndexOf()
function to deal with it.
Upvotes: 0
Reputation: 131
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.
Upvotes: -1
Reputation: 595
myTextCount.split("[\\.\\d]+")
will give you [, kg] which contain the second part, and then use #indexOf() to find the first part.
Upvotes: 1