java - 字符串、模式匹配

标签 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 中实现这一点?

提前谢谢你。

最佳答案

使用正则表达式:

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 上的链接.

关于java - 字符串、模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15218713/

相关文章:

java - Eclipse 中的编译器合规性错误

Android - 去除按下动画上的阴影

java - 可执行 Jar 在类路径上找不到 typesafe/config application.conf

java - 我试图在 Eclipse 中运行 Java,它要求我选择 ant build,而我选择的任何一个都说无法找到要运行的 ant 文件...

java - 一段时间后取消 AsyncTask

android - android中的父子树结构

java - Android Socket UI 错误

java - Android Studio 通过不同的 Activity 计时

java - 需要帮助保存图像文件

java - setMultiChoiceItems 单击时 IndexOutOfBoundsException