正则表达式,提取多个数值中的某一个怎么写
\[\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代码示例
public 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
}
}
}