我在CSV文件中有这种列表:

    4231;"Swiss Federal Railways (SBB; CFF; FFS)"
    67;"Hershey Co; The"


我的目标是清理这些字符串,只保留第一个分号:

4231; Swiss Federal Railways (SBB CFF FFS)
67; Hershey Co The


我试图这样做:

String[] companyDetails =
                    line.replaceAll("\"","").trim().split(";");


但这还不够。

编辑:
更清楚地说,这是我使用的代码:

br = new BufferedReader(new FileReader("/Users/blue/IdeaProjects/matching/src/main/resources/company_list.csv"));

            // Creating a HashSet for holding Company object
            HashSet<Company> companyHashSet = new HashSet<Company>();

            String line;

            // Read to skip the header
            br.readLine();

            // Reading from second line
            while ((line = br.readLine()) != null) {

                String[] companyDetails =
                        line.replaceAll("\"","").trim().split(";");

最佳答案



爪哇

See regex in use here

((?:^[^;\v]*;|\G(?!\A))[^;\v]*);


替代

$1


其他语言(即PCRE)

在其他正则表达式中,您可以使用以下正则表达式,但是Java不支持标记\K(重置报告的匹配项的起点-最终匹配项中将不再包含任何以前使用的字符)。这将使用空字符串代替捕获组。

(?:^[^;\v]*;|\G(?!\A))[^;\v]*\K;




用法

See code in use here

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "((?:^[^;\\v]*;|\\G(?!\\A))[^;\\v]*);";
final String string = "    4231;\"Swiss Federal Railways (SBB; CFF; FFS)\"\n"
     + "    67;\"Hershey Co; The\"";
final String subst = "$1";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);




结果

输入值

     4231;"Swiss Federal Railways (SBB; CFF; FFS)"
     67;"Hershey Co; The"


输出量

     4231;"Swiss Federal Railways (SBB CFF FFS)"
     67;"Hershey Co The"




说明


((?:^[^;\v]*;|\G(?!\A))[^;\v]*)将以下内容捕获到捕获组1中


(?:^[^;\v]*;|\G(?!\A))匹配以下任一


^[^;\v]*;


^在行首声明位置
[^;\v]*匹配集合中不存在的任意数量的任何字符(除分号;或垂直空格以外的任何字符)
;从字面上匹配分号;

\G(?!\A)在上一场比赛的末尾声明位置

[^;\v]*匹配集合中不存在的任意数量的任何字符(除分号;或垂直空格以外的任何字符)

;从字面上匹配分号;

08-04 03:05
查看更多