为了账号安全,请及时绑定邮箱和手机立即绑定

正则表达式,提取多个数值中的某一个怎么写?

/ 猿问

正则表达式,提取多个数值中的某一个怎么写?

比如

内容1:[8175.6,0.0085],[8175.1,0.55],[8175,2.5],[8174.9,1.5],[8174.8,0.814],[8172.1,0.2],[8171.8,0.356],[8171.6,1.32],[8171.5,0.8],[8171.2,0.0615],[8171.1,0.0025],[8170.9,0.2],[8170.2,0.5],[8169.7,0.3843],[8169.6,0.6858],[8169.4,1.836],[8169.2,0.4],[8168.9,0.5152],[8168.8,0.2],[8167.9,0.4],[8167.8,0.4],[8167.5,0.3396],[8165.3,0.2423],[8165.2,0.2],[8165.1,11.1044]

内容2:[8165,8.8056], [8164.9,0.0864], [8164.7,0.48], [8164,0.48], [8163.3,0.0911], [8162,0.009], [8161.7,0.003], [8161.4,4.3], [8161.3,3], [8161,0.55], [8160.8,0.4], [8160.7,0.4], [8160,5.8816], [8159.8,13.0436], [8159.3,0.02], [8159.1,0.0433], [8159,0.4], [8158.8,0.0705], [8158.7,0.4], [8158.5,2.5013], [8156.2,12.5], [8155.3,0.02], [8155.1,0.9989], [8155,11.102], [8153.4,1]

取内容1中第一个数值:8175.6,0.0085 或[8175.6,0.0085]
取内容2中第一个数值:8165,8.8056 或[8165,8.8056]

表达式该怎么写?如果是取最后一个数值,或者其中某个数值呢?
谢谢各位帮忙,十分感激

查看完整描述

1 回答

?
一只名叫tom的猫

\[\d+(\.\d+)?,\d+(\.\d+)?\]   这是匹配一个  类似[8175.6,0.0085]格式字符串的正则表达式

如果你要取第1个数值

\[(\d+(\.\d+)?,\d+(\.\d+)?)\]  这样就可以了,匹配结果的第一组$1就是8175.6,0.0085

如果你要取第5个数值则可以这样

(\[\d+(\.\d+)?,\d+(\.\d+)?\],){4}\[(\d+(\.\d+)?,\d+(\.\d+)?)\]   这时匹配结果的第四组$4是你要的结果

取第7个数值则 (\[\d+(\.\d+)?,\d+(\.\d+)?\],){6}\[(\d+(\.\d+)?,\d+(\.\d+)?)\]  ,依然是结果的第四组是你要的结果

以此类推

如果是取最后一个

(\[\d+(\.\d+)?,\d+(\.\d+)?\],)*\[(\d+(\.\d+)?,\d+(\.\d+)?)\] 依然是取结果的第四组

java代码示例

1234567891011121314151617181920212223public class Demo {    public static void main(String[] args) {        String str = "[8175.6,0.0085],[8175.1,0.55],[8175,2.5],[8174.9,1.5],[8174.8,0.814],[8172.1,0.2],[8171.8,0.356],[8171.6,1.32],[8171.5,0.8],[8171.2,0.0615],[8171.1,0.0025],[8170.9,0.2],[8170.2,0.5],[8169.7,0.3843],[8169.6,0.6858],[8169.4,1.836],[8169.2,0.4],[8168.9,0.5152],[8168.8,0.2],[8167.9,0.4],[8167.8,0.4],[8167.5,0.3396],[8165.3,0.2423],[8165.2,0.2],[8165.1,11.1044]";         Pattern pattern1 = Pattern.compile("\\[(\\d+(\\.\\d+)?,\\d+(\\.\\d+)?)\\]");        Matcher matcher1 = pattern1.matcher(str);        if (matcher1.find()) {            System.out.println("第一个:" + matcher1.group(1));  // 8175.6,0.0085        }         Pattern pattern2 = Pattern.compile("(\\[\\d+(\\.\\d+)?,\\d+(\\.\\d+)?\\],){4}\\[(\\d+(\\.\\d+)?,\\d+(\\.\\d+)?)\\]");        Matcher matcher2 = pattern2.matcher(str);        if (matcher2.find()) {            System.out.println("第五个:" + matcher2.group(4));  // 8174.8,0.814        }                 Pattern pattern3 = Pattern.compile("(\\[\\d+(\\.\\d+)?,\\d+(\\.\\d+)?\\],)*\\[(\\d+(\\.\\d+)?,\\d+(\\.\\d+)?)\\]");        Matcher matcher3 = pattern3.matcher(str);        if (matcher3.find()) {            System.out.println("最后一个:" + matcher3.group(4));  // 8165.1,11.1044        }    }}


查看完整回答
反对 回复 2018-08-20

添加回答

回复

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信