views:

182

answers:

3

I have a string named s_Result which will be parsed from the Internet. The format may be "Distance: 2.8km (about 9 mins)", and there are 4 variables which are f_Distance, m_DistanceUnit, f_timeEst, m_timeEstUnit.

My question is how to parse s_Result and assign 2.8, km, 9, mins into f_Distance, m_distanceUnit, f_timeEst and m_timeEstUnit respectively using regular expression?

I tried using "\d+(\.\d+)?" in RegEx Tester and the result showed 2 matches found, but if I use "\\d+(\\.\\d+)?" in Android code, it showed no matches!

Any suggestions what might be going wrong?

A: 

I tried using "\d+(\.\d+)?" in RegEx Tester and the result showed 2 matches found, but if I use "\\d+(\\.\\d+)?" in Android code, it showed no matches!

Probably you was using String#matches() or Matcher#matches() which would match on the entire string. The regex is then actually "^\\d+(\\.\\d+)?$". Better use Matcher#find() instead.

String s = "Distance: 2.8km (about 9 mins)";
Matcher m = Pattern.compile("\\d+(\\.\\d+)?").matcher(s);
while (m.find()) {
    System.out.println(m.group(0)); // 2.8 and 9
}

That said, have you considered writing a parser?

BalusC
Thanks for your reply!! You are right, i was using `Matcher.matches()`. And your code works fine!! I do consider to write a parser, but there are some problems exist. The major problem is that I can not make sure the format of `s_Result`. All I know is there must exist 2 sets of data in the sting, which including numbers and its unit. Do you have any idea how to get the unit followed by the numbers?? Thanks a lot!!
ChengYing
+2  A: 

Something like that?

String s_Result="Distance: 2.8km (about 9 mins)";

//Distance parsing
Pattern p = Pattern.compile("Distance: (\\d+(\\.\\d+)?)(.*?)\\b");
Matcher m = p.matcher(s_Result);
if(m.find()){
    MatchResult mr=m.toMatchResult();
    f_Distance=mr.group(1);//2.8
    m_DistanceUnit=mr.group(3);//km
}

//Time parsing
p = Pattern.compile("about (\\d+(\\.\\d+)?) (.*)\\b");
m = p.matcher(s_Result);
if(m.find()){
    MatchResult mr=m.toMatchResult();
    f_timeEst=mr.group(1);//9
    m_timeEstUnit=mr.group(3);//min
}

And here's another option for you, to match more flexible format:

String s_Result="Distance: 2.8km (about 9 mins)";
Pattern p = Pattern.compile("(\\d+(\\.\\d+)?) ?(\\w+?)\\b");
Matcher m = p.matcher(s_Result);
while(m.find()){
    MatchResult mr=m.toMatchResult();
    String value=mr.group(1);//2.8 and 9 come here
    String units=mr.group(3);//km and mins come here
}
Fedor
This is exactly what I want!!!! How idiot I am that forgot to use `"\b"`... Thank you so much^^
ChengYing
A: 

It's absolutely the same as in Java.

Really, most of Android questions are not related to Android itself, but to Java programming in general. Please try to search for more general questions before posting new 'Android' questions.

Alexander Kosenkov