How to use a regular expression and assign the result to variables in Android?
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 expre开发者_如何学Cssion?
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?
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
}
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?
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.
精彩评论