如何用java读取字符串到某些逗号

时间:2017-01-17 15:16:30

标签: java string file

我需要读取某个逗号的文件,例如; String s=hii,lol,wow,and,finally

需要输出为hii,lol,wow,and 不要让最后一个逗号后跟字符 因为我的代码正在读取最后一个逗号字符串 示例:我将代码输出为:finally 以下是我的代码 请指导我

File file =new File("C:/Users/xyz.txt");

FileInputStream inputStream = new FileInputStream(file);

String filke = IOUtils.toString(inputStream);

String[] pieces = filke.split("(?=,)");

String answer = Arrays.stream(pieces).skip(pieces.length - 1).collect(Collectors.joining());

String www=answer.substring(1);

System.out.format("Answer = \"%s\"%n", www);

4 个答案:

答案 0 :(得分:1)

您不一定需要使用正则表达式。只需获取最后','的索引并从0获取子字符串到该索引:

String answer = "hii,lol,wow,and,finally";
String www = answer.substring(0, answer.lastIndexOf(','));
System.out.println(www); // prints hii,lol,wow,and

答案 1 :(得分:1)

Java中的

lastIndexOf(String str)有一个名为String s = "hii,lol,wow,and,finally";的方法。这对你来说可能会派上用场。 假设您的输入为String 您可以执行String s = "hii,lol,wow,and,finally"; s = s.substring(0, s.lastIndexOf(",")); 操作,例如:

hii,lol,wow,and

这会为您提供输出:<table th:object="${showbudata}"> <thead> <tr> <th> Date </th> <th> Status </th> <th> HostName </th> <th> Implement Version</th> </tr> </thead> <tbody> <tr th:each="t: ${showbudata}" th:if="${server.host == t.host}"> <td th:text="${t.date}" /> <td th:text="${t.Status}" /> <td th:text="${t.host}" /> <td th:text="${t.version}" /> </tr> </tbody> </table>

答案 2 :(得分:1)

如果您想使用java 8流为您执行此操作,可以尝试过滤?

cd electricity_profiles.git
git push --mirror https://github.com/oliversheridanmethven/electricity_profiles.git

这将打印String answer = Arrays.stream(pieces).filter(p -> !Objects.equals(p, pieces[pieces.length-1])).collect(Collectors.joining());

答案 3 :(得分:0)

要严格正则表达式,您可以使用Pattern.compileMatcher

Pattern.compile("\w+(?=,)");
Matcher matcher = pattern.matcher(filke);
while (matcher.find()) {
   System.out.println(matcher.group(1) + ","); // regex not good enough, maybe someone can edit it to include , (comma)
}

将匹配hii, lol, wow, and, 请参阅此处的正则表达式示例https://regex101.com/r/1iZDjg/1