java-匹配字符串中的正则表达式模式(列出匹配和不匹配的部分)
java-Match a regex pattern in a string(listing matching and non-matching parts)
我有一个包含五个字段的 csv 字符串(3 个必填字段和 2 个可选字段)。可选字段位于位置 3 和 5。
我有一个正则表达式模式来识别双引号中的字符串
private static final String TEXT_IN_DBL_QUOTES_REGEX="\"([^\"]*)\"";
private static final String rowData="\"Field1\", \"Field2\", , \"Field4\", ";
public static void main(String[] args){
List<String> fields = Lists.newArrayList();
Pattern regex = Pattern.compile(TEXT_IN_DBL_QUOTES_REGEX);
Matcher matcher = regex.matcher(rowData);
while(matcher.find()){
fields.add(matcher.group(1));
}
return fields;
}
My expected result is an array list containing
Field1, Field2, null, Field4, null
but the above is returning
Field1, Field2, Field4
如何调整上述代码以获得所需的结果?
您可以像这样调整您的正则表达式:
String TEXT_IN_DBL_QUOTES_REGEX="\"([^\"]*)\"|(?<=,) *(?=,|$)";
String rowData="\"Field1\", \"Field2\", , \"Field4\", ";
List<String> fields = new ArrayList<>();
Pattern regex = Pattern.compile(TEXT_IN_DBL_QUOTES_REGEX);
Matcher matcher = regex.matcher(rowData);
while(matcher.find()) {
fields.add(matcher.group(1));
}
System.out.println (fields);
输出:
[Field1, Field2, null, Field4, null]
我有一个包含五个字段的 csv 字符串(3 个必填字段和 2 个可选字段)。可选字段位于位置 3 和 5。 我有一个正则表达式模式来识别双引号中的字符串
private static final String TEXT_IN_DBL_QUOTES_REGEX="\"([^\"]*)\"";
private static final String rowData="\"Field1\", \"Field2\", , \"Field4\", ";
public static void main(String[] args){
List<String> fields = Lists.newArrayList();
Pattern regex = Pattern.compile(TEXT_IN_DBL_QUOTES_REGEX);
Matcher matcher = regex.matcher(rowData);
while(matcher.find()){
fields.add(matcher.group(1));
}
return fields;
}
My expected result is an array list containing
Field1, Field2, null, Field4, null
but the above is returning
Field1, Field2, Field4
如何调整上述代码以获得所需的结果?
您可以像这样调整您的正则表达式:
String TEXT_IN_DBL_QUOTES_REGEX="\"([^\"]*)\"|(?<=,) *(?=,|$)";
String rowData="\"Field1\", \"Field2\", , \"Field4\", ";
List<String> fields = new ArrayList<>();
Pattern regex = Pattern.compile(TEXT_IN_DBL_QUOTES_REGEX);
Matcher matcher = regex.matcher(rowData);
while(matcher.find()) {
fields.add(matcher.group(1));
}
System.out.println (fields);
输出:
[Field1, Field2, null, Field4, null]