-1

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

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

现在我只想提取“距位置 0.35 英里”。我对“0.35”更感兴趣,以便将此数字与其他数字进行比较。

字符串 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 英里时该怎么办......

4

1 回答 1

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());
    }
}
于 2013-04-19T16:45:22.150 回答