正则表达式表示特定模式的字符串

时间:2013-04-19 16:33:13

标签: java

说我有一个像下面的字符串

String s1 = "This is a new direction. Address located. \n\n\n 0.35 miles from location";

现在我想提取“距离地点0.35英里”。我对“0.35”更感兴趣,将这个数字与其他数字进行比较。

String s1也可以是以下模式。

String s1 = "This is not a new direction. Address is not located. \n\n\n 10.25 miles from location";

String s1 = "This is not a new direction. Address is located. \n\n\n 11.3 miles from location";

请帮助我实现结果。谢谢!

我试过这个

String wholeText = texts.get(i).getText();
if(wholeText.length() > 1) {
    Pattern pattern = Pattern.compile("[0-9].[0-9][0-9] miles from location");
    Matcher matcg = pattern.matcher(wholeText);
    if (match.find()) {
        System.out.println(match.group(1));
    }

但是当它是xx.xx里程时我不知道该怎么做......

1 个答案:

答案 0 :(得分:2)

这适用于任何格式为... ab.cd ...

的数字
public static void main(String[] args){
    String s  = "This is a new direction. Address located. " +
            "\n\n\n 0.35 miles from location";
    Pattern p = Pattern.compile("(\\d+\\.\\d+)");
    Matcher m = p.matcher(s);
    while (m.find()) {
      System.out.println(m.group());
    }
}