【发布时间】:2020-03-17 22:14:47
【问题描述】:
我有一个相对简单的 java 问题。我有一个看起来像这样的字符串:
"Anderson,T",CWS,SS
我需要以我拥有的方式解析它
Anderson,T
CWS
SS
全部作为单独的字符串。
谢谢!
【问题讨论】:
-
您正在尝试解析逗号分隔值 (csv),引用值通常用于 csv。有图书馆可以阅读这种格式。
我有一个相对简单的 java 问题。我有一个看起来像这样的字符串:
"Anderson,T",CWS,SS
我需要以我拥有的方式解析它
Anderson,T
CWS
SS
全部作为单独的字符串。
谢谢!
【问题讨论】:
这是一个捕获带引号的字符串、删除空格和匹配空项的解决方案:
public static void main(String[] args) {
String quoted = "\"(.*?(?<!\\\\)(?:\\\\\\\\)*)\"";
Pattern regex = Pattern.compile(
"(?:^|(?<=,))\\s*(" + quoted + "|[^,]*?)\\s*(?:$|,)");
String line = "\"Anderson,T\",CWS,\"single quote\\\"\", SS ,,hello,,";
Matcher m = regex.matcher(line);
int count = 0;
while (m.find()) {
String s = m.group(2) == null ? m.group(1) : m.group(2);
System.out.println(s);
count++;
}
System.out.printf("(%d matches found)%n", count);
}
我将模式中的引用部分分开,以便更容易理解。捕获组 1 是带引号的字符串,2 是每隔一个匹配项。
分解整体格局:
(?:^|(?<=,))(不要捕获)\\s* (" + quoted + "|[^,]*?)
(非逗号匹配是非贪婪的,因此它不会抓取任何后续空格)\\s* (?:$|,)(不要捕获)分解引用模式:
\"
(
.*?的最小匹配
(?<!\\\\)(?:\\\\\\\\)*(以避免匹配带有或不带有前面转义反斜杠的转义引号))
\"
【讨论】:
, 开头,这并不总是有效 - 通过交换逗号前瞻/后向逻辑进行修复
假设你的字符串是这样的
String input = "\"Anderson,T\",CWS,SS";
您可以使用针对类似情况找到的this 解决方案。
String input = "\"Anderson,T\",CWS,SS";
List<String> result = new ArrayList<String>();
int start = 0; //start index. Used to determine where the word starts
boolean inQuotes = false;
for (int current = 0; current < input.length(); current++) { //iterate through characters
if (input.charAt(current) == '\"') //if found a quote
inQuotes = !inQuotes; // toggle state
if(current == (input.length() - 1))//if it is the last character
result.add(input.substring(start)); //add last word
else if (input.charAt(current) == ',' && !inQuotes) { //if found a comma not inside quotes
result.add(input.substring(start, current)); //add everything between the start index and the current character. (add a word)
start = current + 1; //update start index
}
}
System.out.println(result);
我对其进行了一些修改以提高可读性。此代码将您想要的字符串存储在列表result 中。
【讨论】: