用于拆分由|分隔的字符串的正则表达式当没有用双引号括起来时 [英] Regex for splitting a string delimited by | when not enclosed on double quotes
本文介绍了用于拆分由|分隔的字符串的正则表达式当没有用双引号括起来时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个正则表达式来计算java中管道分隔字符串中的列数。
列数据将始终用双引号括起来,否则它将为空。
I need a regex to count the number of columns in a pipe delimited string in java. The column data will always be enclosed by double quotes or it will be empty.
例如:
"1234"|"Name"||"Some description with ||| in it"|"Last Column"
以上内容应计为5列,包括名称列后的一列空列。
The above should be counted as 5 columns including one empty column after "Name" column.
谢谢
推荐答案
这是一种方法:
String input =
"\"1234\"|\"Name\"||\"Some description with ||| in it\"|\"Last Column\"";
// \_______/ \______/\/\_________________________________/ \_____________/
// 1 2 3 4 5
int cols = input.replaceAll("\"[^\"]*\"", "") // remove "..."
.replaceAll("[^|]", "") // remove anything else than |
.length() + 1; // Count the remaining |, add 1
System.out.println(cols); // 5
IMO虽然不是很强大。例如,如果你计划处理转义引号,我建议不要使用正则表达式。
IMO it's not very robust though. I wouldn't recommend using regular expressions if you plan on handling escaped quotes, for instance.
这篇关于用于拆分由|分隔的字符串的正则表达式当没有用双引号括起来时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文