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

时间:2022-05-31 21:39:41

Say I have a String like below

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

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

now I want to extract "0.35 miles from location" only. I'm more interested in "0.35" to compare this number with something else.

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

The String s1 may be of following pattern as well.

String s1也可以是以下模式。

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

or

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

Pls help me to achieve the result. Thanks!

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

I tried this

我试过这个

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));
    }

But I don't know what to do when it's xx.xx miles...

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

1 个解决方案

#1


2  

This should work for any number formatted as ...ab.cd...

这适用于任何格式为... 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());
    }
}

#1


2  

This should work for any number formatted as ...ab.cd...

这适用于任何格式为... 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());
    }
}