【问题标题】:how to read string upto certain comma with java如何用java读取字符串到某个逗号
【发布时间】:2017-01-17 15:16:30
【问题描述】:

例如,我需要读取一个文件,直到某个逗号; 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);

【问题讨论】:

  • 与您的代表。你应该知道how to format问题..
  • 必须是正则表达式吗?为什么不删除最后一个, +++
  • 一些子字符串和 lastIndexOf 可能是你需要的
  • 所以像你一样使用 split(),忽略最后一个元素。
  • @String hi,你能考虑stackoverflow.com/help/someone-answers吗?谢谢;)

标签: java string file


【解决方案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

【讨论】:

    【解决方案2】:

    Java 中的String 有一个名为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

    【讨论】:

      【解决方案3】:

      如果你想使用 java 8 流来为你做这件事,可以试试 filter 吗?

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

      这将打印Answer = "hii,lol,wow,and"

      【讨论】:

        【解决方案4】:

        要拥有严格的正则表达式,您可以使用 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

        【讨论】:

          猜你喜欢
          • 2021-08-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-19
          相关资源
          最近更新 更多