字符串,模式匹配

时间:2013-03-05 08:08:55

标签: java android

我可以像这样构建字符串:

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 Warwick Avenue(679871)的房产短信

我想要检索,“(714)321-2620 ”& “ 690 Warwick Avenue(679871)”来自输入

任何人都可以给出指针,如何在Java或Android中实现这一点?

提前谢谢。

2 个答案:

答案 0 :(得分: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上的链接。

答案 1 :(得分:0)

这很容易,同时也很难。

基本上,您可以轻松地使用String.split()将字符串拆分为正则表达式或首次出现的字符。

但是,您需要有一个清晰的模式来检测电话号码和地址。这取决于您自己对这些信息可能性的定义。

相关问题