2017-02-14 75 views
0

我一直試圖提取部分字符串。我在Android應用程序(Java)中執行此操作。Java(Android) - 在2個特定單詞之間提取部分字符串

我的問題是,我將不得不啓動了這樣一個字符串:

位置[融合20.,-30.9876 ACC = 20(...)

表示設備的當前座標(我在此設置了20和-30)以及其他一些測量。我想從該字符串中提取2個座標(它們將始終位於「融合」和「acc」之間),並將它們存儲爲浮點數。

我環顧四周,得出結論認爲可能需要正則表達式來解決這個問題,但請記住,我以前只使用了正則表達式,而且我對它們仍然很缺乏經驗。

任何有關如何解決這個問題的指導將不勝感激!

+0

使用String.split() https://www.tutorialspoint.com/java/java_string_split.htm –

+1

如果協調器之前和之後總是有空格,那麼您可以同時獲得coo沒有RegEx使用的rdinators。 'String location =「Location [fused 20.,-30.9876 acc = 20」; location = location.substring(location.indexOf(「」),location.lastIndexOf(「」)); String locationArr [] = location.split(「,」); System.out.println(「lat:」+ locationArr [0]); System.out.println(「long:」+ locationArr [1]);' –

回答

1

RegExr是學習和構建正則表達式的一個偉大的網站: http://regexr.com/

與此正則表達式匹配的字符串會給你2個座標:

fused\s(-?\d+\.\d+),(-?\d+\.\d+)\s 

拷貝表達RegExr看到每個什麼這些字符的意思。

在Java中使用正則表達式的表情,你需要確保你逃避反斜槓字符(添加一個額外的反斜槓)

在Java:

public static void main(String[] args) { 
    String yourString = "Location[fused 20.,-30.9876 acc=20 "; 

    Pattern pattern = Pattern.compile("fused\\s(-?\\d+\\.\\d+),(-?\\d+\\.\\d+)\\s"); 
    Matcher matcher = pattern.matcher(yourString); 
    if(matcher.find()) { 
     String coordinate1 = matcher.group(1); 
     String coordinate2 = matcher.group(2); 
     System.out.println(coordinate1); 
     System.out.println(coordinate2); 
    } 
} 

輸出:

20.
-30.9876 
+0

它完美的工作!並感謝您的提示,我不知道那個網站。它看起來對於練習正則表達式非常有用 –

相關問題