[英]Regex to read the following formatted string pattern
I want to read and map the following formatted lines into java bean 我想阅读以下格式的行并将其映射到java bean中
80 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) (5,30.18,€9)
7 : (1,10.02,€5) (2,8.2,€9) (3,7.8,€2) (4,7.0,€6) (5,3.18,€9)
So here the digit before : will be captured as a int value and will be mapped on totalWeight and repetive patterns like (1,53.38,€45) will be mapped to items 因此,这里的:之前的数字将被捕获为一个int值,并将被映射到totalWeight上,并且重复性模式(例如(1,53.38,€45))将被映射到项
Here is my java bean 这是我的java bean
public class Package {
private double maxWeigh; \\ so the digit value before : will be here
private List<Product> products; \\ (1,53.38,€45) will be parsed to product class
public double getMaxWeigh() {
return maxWeigh;
}
public void setMaxWeigh(double maxWeigh) {
this.maxWeigh = maxWeigh;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
Here is my product class 这是我的产品类别
public class Product {
private int index;
private double weight;
private double cost;
private String currencySymbol;
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public String getCurrencySymbol() {
return currencySymbol;
}
public void setCurrencySymbol(String currencySymbol) {
this.currencySymbol = currencySymbol;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
This is what i tried so far but this is for only products part i want to capture whole line at once 这是我到目前为止尝试过的方法,但这仅适用于我想一次捕获整条生产线的产品部分
\\((\\d+),(\\d+\\.?\\d*?),€?(\\d+)\\)
Here is a code that lets you iterate over each token (a,b,c) and retrieve their members. 这是一个代码,可让您遍历每个令牌(a,b,c)并检索其成员。
It uses named capturing groups . 它使用命名的捕获组 。
import java.util.regex.*;
public static void main(String[] args) {
Pattern headPattern = Pattern.compile("^(\\d+).*");
Pattern tailPattern = Pattern.compile("\\((?<p1>\\d),(?<p2>\\d+\\.\\d+),(?<p3>€\\d+)\\)");
Matcher m1 = headPattern.matcher("80 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) (5,30.18,€9)");
Matcher m2 = tailPattern.matcher("80 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) (5,30.18,€9)");
m1.matches();
System.out.println("p0 = " + m1.group(1));
while(m2.find()) {
System.out.println("token = " + m2.group());
System.out.println("p1 = " + m2.group("p1"));
System.out.println("p2 = " + m2.group("p2"));
System.out.println("p3 = " + m2.group("p3"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.