2013-11-24 57 views
2

我怎麼可以拆分100.26千克爲System.out.println作爲分割字符串浮動和字符串

100.26 
kg 

我試圖做使用(「\ d +」),但沒有成功。

​​

100.26kg可能根據用戶輸入而有所不同。它可能是100.26千克,100克,100磅或100升。如果有任何方法可以分割數字和字母,這將是非常有幫助的

+0

如果有'#kg'一個固定的格式,其中''#是任何數字,不要使用正則表達式。 – Maroun

回答

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

不要使用Split,只需使用String.IndexOf()函數來處理它。

1

嘗試環視正則表達式,

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

如果你想與數分割case-insensitive不是使用(?i)

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

千克不是固定格式。它可以是磅,加侖,升等。這就是爲什麼我需要拆分整數和字符串 – user3003233

+0

@ user3003233,我已經更新了我的答案。 – Masudul

0

myTextCount.split("[\\.\\d]+")會給你[,公斤]包含第二部分,然後使用#indexOf()查找第一部分。

0

試試這個:

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

該解決方案是相當模塊化爲好。

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

產量:

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