2017-09-19 46 views
0

之間的文本如何在Java中使用正則表達式這種格式的每行的大小/重量屬性?我們老師給我們的文本文件使用了不同的字符代碼,這就是爲什麼那些奇怪的問號字符存在。使用正則表達式來獲取空白字符和

Popcorn     Butter        6�pkg   3.99 
Laundry Detergent   2X Ultra Free Clear    50�oz   11.99 

獲取空白字符和 之間的文本就足夠了。

+0

'\ S(。+)\ u1234'(其中符號的'\ u1234'代碼),並獲得第一組 – ZhenyaM

+0

也許這是可以用' 「\\ d +」'匹配數字序列。但是你必須找到並提取合適的子字符串。 – laune

回答

1

嘗試使用這個表達式\s+(\d+)�,如果你不知道,如果結果是一個數字或者不是你可以使用.*\s+(.*?)�而不是任何字符空格和符號之間的匹配:

String[] strs = { 
    "Popcorn     Butter        6�pkg   3.99", 
    "Laundry Detergent   2X Ultra Free Clear    50�oz   11.99" 
}; 

String regex = "\\s+(\\d+)�"; 
Pattern pattern = Pattern.compile(regex); 
for (String str : strs) { 
    Matcher matcher = pattern.matcher(str); 
    while (matcher.find()) { 
     System.out.println(matcher.group(1)); 
     //        ^------note to get the group one 
    } 
} 

輸出

6 
50 
相關問題