2017-08-09 105 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)); 
    } 

就像安德烈亚斯之前说的,你应该使用模式和正则表达式来查找您的字符串信息的组,然后你可以安全的在他们的变量,现在我只打印了出来。

相关问题