2017-08-09 159 views
-5

例如我有String info = "You have 2$ on your public transport card and one active ticket which expires on 2017-08-09 23.59",我只想得到它的兩部分"2$""one active ticket which expires on 2017-08-09 23.59"如何將字符串從一個單詞分解到另一個單詞?

我試圖用split()做到這一點,但我無法找到如何在互聯網上從一個詞拆分到另一個詞。另外我不能改變String info,因爲我從外部服務器獲取它。

+1

不要爲此使用'split()'。使用'Pattern'在模式中應用** regex **模式和*捕獲組*來提取您需要的值。如果你還不知道正則表達式,那麼不是你學習的好時機。這是一個正則表達式的例子:[regex101.com](https://regex101.com/r/QyUSpJ/1/) – Andreas

回答

0

此代碼應該工作。

String info = "You have 2$ on your public transport card and one active ticket which expires on 2017-08-09 23.59"; 
    Pattern pattern = Pattern.compile("(\\d\\$).*and\\s(.*)"); 
    Matcher m = pattern.matcher(info); 
    while (m.find()) { 
     System.out.println("First Group: " + m.group(1) + " \nSecond Group: " + m.group(2)); 
    } 

就像安德烈亞斯之前說的,你應該使用模式和正則表達式來查找您的字符串信息的組,然後你可以安全的在他們的變量,現在我只打印了出來。

相關問題