我可以这样构建字符串:
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/