猿问

如何用逗号分割字符串,后跟一个字母数字字符

我试图通过使用 BufferedReader 来分离一个非常大的 .cvs(255 列),该 BufferedReader 抓取每一行并将其存储在一个字符串中。

我希望能够通过命令和字母来拆分它。前任:

1,2,3,5,6将拆分为
1 | 2 | 3 | 4 | 5 | 6 | 7

hello,world,good day to you, Sir,test会分裂成
你好| 世界| 先生,祝您有美好的一天| 测试

请注意我如何只分隔一个逗号,后面跟一个字母数字。空格前面的逗号不分开,而是句子的一部分。


梵蒂冈之花
浏览 182回答 3
3回答

jeck猫

对于每个字符串a:a.split(",(?=\\S)");

人到中年有点甜

要使用逗号分隔,后跟字母数字字符,您可以使用String pattern = ",(?=\\p{Alnum})";或者,如果您计划支持任何 Unicode 字母,请在模式旁边传递Pattern.UNICODE_CHARACTER_CLASS( ) 选项:(?U)String pattern = "(?U),(?=\\p{Alnum})";请参阅RegexPlanet 正则表达式演示。Java演示:String s = "hello,world,good day to you, Sir,test,1,2";String[] result = s.split(",(?=\\p{Alnum})");for (String r:result) {    System.out.println(r); }输出:helloworldgood day to you, Sirtest12

慕斯王

在此链接中,有一个答案解释了Lookahead 和 Lookbehind的使用。在这里我留下一个我相信可以解决你描述的问题的代码:private static String[] mySplit(final String line, final char separator) {&nbsp; &nbsp; String regex = "((?<=(" + separator + "\\w)|(?=(" + separator + "\\w))))";&nbsp; &nbsp; String[] split = line.split(regex);&nbsp; &nbsp; List<String> list = new ArrayList<>();&nbsp; &nbsp; for (int i = 0; i < split.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; String token = split[i];&nbsp; &nbsp; &nbsp; &nbsp; if (token.startsWith(String.valueOf(separator))) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; split[i + 1] = token.substring(1) + split[i + 1];&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.add(token);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return list.toArray(new String[list.size()]);}private static String concatenate(final String[] tokens, final char separator){&nbsp; &nbsp; StringBuilder builder = new StringBuilder();&nbsp; &nbsp; for (int i = 0; i < tokens.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; builder.append(tokens[i]).append((i < tokens.length - 1) ? separator : "");&nbsp; &nbsp; }&nbsp; &nbsp; return builder.toString();}public static void main(String[] args) {&nbsp; &nbsp; final String line = "hello,world,good day to you, Sir,test";&nbsp; &nbsp; final String[] tokens = mySplit(line, ',');&nbsp; &nbsp; final String newLine = concatenate(tokens, '|');&nbsp; &nbsp; System.out.println("newLine = " + newLine);}
随时随地看视频慕课网APP

相关分类

Java
我要回答