【问题标题】:Replace a string with some part of a text file用文本文件的某些部分替换字符串
【发布时间】:2017-08-30 08:12:01
【问题描述】:

我想在文件中找到一个编号模式(我已经成功),通过使用类中的另一种方法(我也成功)将其转换为我想要的数字格式...

我的问题是我想用以前的数字格式(我不知道如何)替换新的数字格式并将其写入新文件。

  String INPUT = "D:\\input.txt";
  String OUTPUT = "D:\\output.txt";
  String all = "";
  Pattern regexp = Pattern.compile("\"(\\d{14}.{2}\\d{4})\"");
  try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(INPUT), "UTF-8"))) {
        String CurrentLine;
        while ((CurrentLine = in.readLine()) != null) {
            Matcher matcher = regexp.matcher(CurrentLine);
              if (matcher.find()) {
                  String number1 = CurrentLine.substring(10,20);
                  String number2 = CurrentLine.substring(30,40);
                  number1 = convertor(number1);
                  number2 = convertor(number2);
              }
            all = all + sCurrentLine + "\r\n";  \\create output to use for BufferedWriter
        }

顺便说一句,上面的代码(很明显)只是我整个代码的一部分。

【问题讨论】:

  • 尚不清楚转换器的作用...
  • 假设数字格式是这样的: 23+3 转换器方法将数字相加并返回 26+0。输入是 20 个字符,转换器输出也是 20 个字符。

标签: java regex file replace


【解决方案1】:

要保存您的输出,只需在循环结束时执行此操作即可。

Files.write(Paths.get(OUTPUT), all.getBytes(), StandardOpenOption.CREATE);

matcher 对象甚至返回组 (\d{14}.{2}\d{4}) 匹配的位置。我建议仔细检查这部分代码以帮助自己。

使用matcher.start(1) 获得该组在上一次匹配操作期间捕获的子序列的起始索引。

【讨论】:

  • 我确切地知道在这些行(有数字)中找到字符串的位置。这个 matcher.start(1) 能帮我替换转换后的模式吗?
  • 这只是一个建议......如果你到目前为止已经知道该怎么做那么好
  • 谢谢,但是如何将转换后的数字替换为原始数字?
  • 不,因为我不明白它会做什么。我只是自己解决了。我只是简单地将“CurrentLine”替换为我想要的数字-使用replaceAll-然后将其保存到字符串“all”。然后我写了“全部”。完成。
猜你喜欢
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-31
  • 2018-04-08
  • 2018-07-14
  • 1970-01-01
相关资源
最近更新 更多