gpt4 book ai didi

java - CSV 文件模式匹配也匹配分隔符

转载 作者:行者123 更新时间:2023-12-02 02:49:30 24 4
gpt4 key购买 nike

我使用了这个正则表达式 (?:^|;)\s*(?:(?:(?=")"([^"].*?)")|(?:(? !")(.*?)))(?=;|$) 稍微改编自 this question 中的解决方案

我的问题是它也匹配分隔分号,然后我必须手动删除它,这是不好的风格。

String separator = ";";
String patternString = "(?:^|" + separator + ")\\s*(?:(?:(?=\")\"([^\"].*?)\")|(?:(?!\")(.*?)))(?=" + separator + "|$)";
pattern = Pattern.compile(patternString);

Matcher match = pattern.matcher(line);
// Find all cells and add them to row.
while (match.find())
{
String cell = match.group();
//HACK something with the pattern to match is wrong
if(cell.indexOf(";") == 0) cell = cell.substring(1);
cell = unescapeCsv(cell);
//do something with cell
}

我尝试匹配它,它必须匹配被引用且分号作为数据一部分的列(参见最后一列):

Name;inst_type;Position;Currency;cftype;amount;tenor;fwterm;compoundtype;resetterm;histrates;sdate;edate;fwdate;callput;capfloor;strike;vola;volavalue;ulspot;ulspotvalue;divcurve;cleanflag;fixrate;compfr;dayc;refindex;spread;floatfactor;paystart;payend;annuity;amortizingtype;cgm;resrate;nextrate;isprorated;rolldate;rollday;islongstub;isarrear;payrule;paydays;paycal;resrule;resdays;rescal;isfixcoupon;spreadcurve;cds_spread_value;recovrate;payoutrate;payrec;creditspread;disc;"C""F"
Bond1;;1;EUR;2;100;6M;;;;;01.09.2007;01.09.2010;;;;;;;;;;;0,0625;1;1;;;;0;100;;;1;;;1;01.06.2008;;1;;;;;;;;;;;;;;;IR-EUR;"2;01062008;100;0;0.0625;;01092007;01062008";"2;01122008;100;0;0.0625;;01062008;01122008";"2;01062009;100;0;0.0625;;01122008;01062009";"2;01122009;100;0;0.0625;;01062009;01122009";"2;01092010;100;0;0.0625;;01122009;01092010";"1;01092010;100";
Bond2;;1;EUR;2;100;6M;;;;;01.09.2007;01.09.2010;;;;;;;;;;;0,0625;1;1;;;;0;100;;;-1;;;1;;;;;;;;;;;;;;;;;;IR-EUR;"2;01092010;100;0;0.0625;;01032010;01092010";"2;01032010;100;0;0.0625;;01092009;01032010";"2;01092009;100;0;0.0625;;01032009;01092009";"2;01032009;100;0;0.0625;;01092008;01032009";"2;01092008;100;0;0.0625;;01032008;01092008";"2;01032008;100;0;0.0625;;01092007;01032008";"1;01092010;100";

最佳答案

试试这个,它应该可以工作:(?<=^|;)".*?"(?=;|$)|(?<=^|;)[^;]*(?=;|$)

说明

(?<=^|;)".*?"(?=;|$)双引号零到无限次之间的任何字符,前面是开始 anchor 或分号,后面是分号或结束 anchor

|

(?<=^|;)[^;]*(?=;|$)除分号外的任何字符,前有开始 anchor 或分号,后有分号或结束 anchor ,零到无限次

Use * instead of + is important to match empty columns

Demo

关于java - CSV 文件模式匹配也匹配分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44066703/

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