2013-03-05 130 views
1

我可以生成字符串是這樣的:字符串,模式匹配

String str = "Phone number %s just texted about property %s"; 
String.format(str, "(714) 321-2620", "690 Warwick Avenue (679871)"); 

//Output: Phone number (714) 321-2620 just texted about property 690 Warwick Avenue (679871) 

我想實現的是反向的這一點。輸入將下面的字符串

電話號碼(714)321-2620只是發短信約690物業華威大道(679871)

我想要檢索, 「(714)321-2620」 & 「690 Warwick Avenue(679871)」from input

任何人都可以給指針,如何在Java或Android中實現這一點?

預先感謝您。

+0

拖放*電話號碼*和*只是發短信關於財產*。然後將新的字符串分成兩部分。你會得到你所需要的。這裏是[Android中的字符串](http://developer.android.com/reference/java/lang/String.html)。 – 2013-03-06 08:29:29

回答

7

使用正則表達式:

String input = "Phone number (714) 321-2620 just texted about property 690 Warwick Avenue (679871)"; 
Matcher m = Pattern.compile("^Phone number (.*) just texted about property (.*)$").matcher(input); 
if(m.find()) { 
    String first = m.group(1); // (714) 321-2620 
    String second = m.group(2); // 690 Warwick Avenue (679871) 
    // use the two values 
} 

完整的工作代碼:

import java.util.*; 
import java.lang.*; 
import java.util.regex.*; 

class Main 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
    String input = "Phone number (714) 321-2620 just texted about property 690 Warwick Avenue (679871)"; 
    Matcher m = Pattern.compile("^Phone number (.*) just texted about property (.*)$").matcher(input); 
    if(m.find()) { 
     String first = m.group(1); // (714) 321-2620 
     String second = m.group(2); // 690 Warwick Avenue (679871) 
     System.out.println(first); 
     System.out.println(second); 
    } 
} 

而且在ideone的鏈接。

+0

非常感謝。這是我正在尋找的。 – Veer 2013-03-05 09:29:39

+0

嗨,有人可以解釋嗎? – 2013-03-05 09:44:21

+1

@MehulJoisar它非常簡單 - '^'代表您匹配'$'的字符串的開始 - 結束。所以你只關心匹配整個字符串的匹配。 '(。*)'是匹配組,它們將匹配任何符號序列。 'm.group(1)'會返回第一個這樣的組和'group(1)' - 第二個。匹配字符串中的其餘符號與您匹配的字符串中的字符只是一對一地匹配。希望能夠說清楚。 – 2013-03-06 08:53:28

0

這很簡單,同時很難。

基本上,你可以很容易地使用String.split()來分割正則表達式中的字符串或首次出現的字符。

但是,您需要有一個清晰的模式來檢測電話號碼和地址。這取決於你自己對這些信息可能性的定義。