【问题标题】:String get text at the end of lineString 获取行尾的文本
【发布时间】:2015-02-11 12:11:24
【问题描述】:

我有一个 .txt 文件,其中包含如下文本:

blah blah blah size: 80

blah blah blah blah size: 150

Aka 有一些文本,然后是 size:spaceintnew line,重复...现在,我需要获取该整数并将其存储到变量中。我使用 BufferedReader 逐行读取文本,一切正常,但是,仅仅因为该整数的长度不同,我无法判断例如:

String x = line.substring(line.indexOf("size") + 6, line.indexOf("size") + 8)

因为如果 size 有 3 位,它只会得到前两位。有什么建议?

【问题讨论】:

  • 所以不要使用固定偏移量。向后扫描字符串以查找遇到的第一个空格,然后将其用作提取数字的起点。
  • 为什么不在“:”字符上分行呢?

标签: java regex string substring bufferedreader


【解决方案1】:

您可以使用String#substring(beginIndex) 方法获取从指定索引开始直到字符串结尾的子字符串:

String x = line.substring(line.indexOf("size") + 6);

【讨论】:

  • 我很确定这是very false
  • @snickers10m 我只使用了一个参数,即开始索引。您提供的链接用于不同的签名。
  • 抱歉,我以为您是在说您的示例是 only 选项。
  • 不用担心。我更新了答案以使其更清楚。
【解决方案2】:

如何使用最后一个空格的位置来确定子字符串从哪里开始?

String s = line.substring(line.lastIndexOf(' ')+1);

【讨论】:

    【解决方案3】:

    你也可以split字符串并访问最后一个元素

    String[] split = s.split(":");
    System.out.println(split[1].trim());
    //                       ^-this is just an example, as an exercise try 
    //                         to figure out index of last element yourself
    

    【讨论】:

    • 这是我的建议,不想为他做这项工作......永远不要那样学习!
    • @SuncoastOwner 这也是我想到的第一个方法。我想知道为什么 OP 不使用这种方法并依赖空白索引?
    【解决方案4】:

    你可以试试正则表达式,下面的表达式获取数字组:

    // can run in a for loop for each line
    String regEx = ".*size:\s+(\d+)";
    Pattern pattern = Pattern.compile(regEx);
    Matcher matcher = pattern.matcher(line); // line to match
    if (matcher.matches()) {
        String sizeVal = matcher.group(1);
    }
    

    【讨论】:

      【解决方案5】:

      获取冒号后的子串

      String x = line.substring(line.indexOf(":") + 2);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-07
        • 2013-03-25
        • 1970-01-01
        相关资源
        最近更新 更多