我有一个名为 s_Result 将被从互联网上分析的字符串。该格式可以是距离:2.8公里(约9分钟),并有4个变量,是 f_Distance , m_DistanceUnit , f_timeEst , m_timeEstUnit 。
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.
我的问题是如何解析 s_Result 并指定 2.8 ,公里, 9 ,分钟到 f_Distance , m_distanceUnit , f_timeEst 和 m_timeEstUnit 分别使用常规的前pression?
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?
我试图用\ D +(\。\ D +)?的正则表达式测试,结果显示发现2场比赛,但如果我用\\ D +(\\ \\ D +)? Android中code,这表明没有匹配!
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?
推荐答案类似的东西?
String s_Result="Distance: 2.8km (about 9 mins)"; //Distance parsing Pattern p = Patternpile("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 = Patternpile("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 = Patternpile("(\\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 }更多推荐
如何使用常规的前pression,结果在Android中的变量赋值?
发布评论