如何使用常规的前pression,结果在Android中的变量赋值? [英] How to use a regular expression and assign the result to variables in Android?

查看:138
本文介绍了如何使用常规的前pression,结果在Android中的变量赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 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 = 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
}

这篇关于如何使用常规的前pression,结果在Android中的变量赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆