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) "を取得したい

JavaまたはAndroidでこれを達成する方法を教えてください。

前もって感謝します。

4

2 に答える 2

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のリンク。

于 2013-03-05T08:20:21.190 に答える
0

これは簡単ですが、同時にかなり難しいです。

基本的に、String.split()を使用するだけで、正規表現または文字の最初の出現で文字列を部分的に分割することが簡単にできます。

ただし、電話番号と住所がどこにあるかを検出するには、明確なパターンが必要です。これは、これらの情報の可能性についてのあなた自身の定義に依存します。

于 2013-03-05T08:19:44.567 に答える