gpt4 book ai didi

java - 正则表达式读取以下格式化字符串模式

转载 作者:行者123 更新时间:2023-12-02 02:36:46 25 4
gpt4 key购买 nike

我想读取以下格式化行并将其映射到 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)

因此,这里 : 之前的数字将被捕获为 int 值,并将映射到 TotalWeight 上,并且像 (1,53.38,€45) 这样的重复模式将映射到项目

这是我的 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;
}
}

这是我的产品类别


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;
}



}


这是我到目前为止所尝试的,但这仅适用于我想立即捕获整条产品线的产品部分

\\((\\d+),(\\d+\\.?\\d*?),€?(\\d+)\\)

最佳答案

下面的代码可让您迭代每个标记(a、b、c)并检索其成员。
它使用 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"));
}
}

关于java - 正则表达式读取以下格式化字符串模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57199495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com