[英]Returning substring of string after first occurence of a comma
How can I take this input CSV file: 如何获取此输入CSV文件:
0,1
1,2
3,4
5,6,7
8,10
9,10
and return only the substring of each line after the first occurrence of "," so that my output is: 并仅在首次出现“,”之后返回每行的子字符串,因此我的输出是:
1
2
4
6,7
10
10
I can only figure out how to parse the string within a certain range after splitting by commas, so I am using string.split(",")[1]
to return everything after the first comma and before the next comma but I can't figure out how to get everything after the first comma. 在用逗号分割后,我只能弄清楚如何在一定范围内解析字符串,因此我使用string.split(",")[1]
返回第一个逗号之后和下一个逗号之前的所有内容,但是我可以请弄清楚如何在第一个逗号后得到所有内容。 So for the inputs with more than one comma, I'm missing data. 因此,对于带有多个逗号的输入,我缺少数据。
你可以做:
line.substring(line.indexOf(",")+1)
There are a couple of different ways of removing everything before the first occurrence of a ,
. 有一对夫妇的去除的第一次出现之前,一切都不同的方式,
。
,
and substring using that index. 查找第一个的索引(位置) ,
并使用该索引创建子字符串 。 This would look like 这看起来像
String wantedPart = lineOfText.substring(lineOfText.indexOf(",") + 1);
Since indexOf
returns the index of the ,
itself, you need to add one to get everything past it. 由于indexOf
返回的索引,
它本身,你需要添加一个让一切过去吧。
String.split(String regex, int limit)
. 使用更好的重载,如String.split(String regex, int limit)
。 This overload allows you to match a maximum of limit
substrings. 此重载允许您匹配最大limit
子字符串。 So with a limit of 2, it will split on the first ,
found (and no more). 因此,与2的限制,它会分裂第一,
发现(并没有更多)。 In your code, you could use 在您的代码中,您可以使用
String wantedPart = lineOfText.split(",")[1];
If a shell script will do, you can use the cut
command: 如果要使用Shell脚本,则可以使用cut
命令:
-d ','
means use a comma as -f2-
means use fields 2 onwards. -d ','
表示使用逗号, -f2-
表示使用字段2起。
Machine:~ donald$ cat file.txt
0,1
1,2
3,4
5,6,7
8,10
9,10
Machine:~ donald$ cat file.txt | cut -d ',' -f2-
1
2
4
6,7
10
10
Machine:~ donald$
尝试使用String.indexOf(“,”)等。
You can use the overloaded split method which allows to define a limit of substrings. 您可以使用重载的split方法,该方法允许定义子字符串的限制。
split(",",1) split(“,”,1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.