简体   繁体   English

Java搜索文本文件的字符串,并替换或删除字符串中的字符

[英]Java search text file for string and replace or remove a character within the string

I'm working with a large text file that has thousands of lines of text that contain some information. 我正在使用一个包含数千行文本的大型文本文件,其中包含一些信息。 Sometimes the software will randomly add a character in place which will fail our upload. 有时,软件将随机添加一个将无法上传的角色。 I'm trying to create a program that finds a string that is hard coded and then searches within the line and replaces or removes the invalided character. 我正在尝试创建一个程序,找到一个硬编码的字符串,然后在该行内搜索并替换或删除无效字符。 Here is some of the contents of the text file. 以下是文本文件的一些内容。

    MTR17000386001000000000000000RA              124359      
    00010000004000000040000000 000NN  NNE 000                       N    
    RDG17000386 
    KWHL000000000R00000100000059534000405162019075929N000400000010N8486     
    000010500R 00000010010000059226           
    RFF1700038652126007      ERT      
    0000000952.0062500070014051620190759290005953476Type 7  0000N    6
    MTR17000386001000000000000000RA              114818      
    00010000005000000050000000 000NN  NNE 000                       N    
    RDG17000386 
    DMDL000000000R000001000.0072666035305162019112344N000100000010N8486     
    005180500R 00000010010000072666           
    RFF1700038611861733      ERT      
    0000000952.0062500070000051620191123440007266680Type 7  0000N    6

On the line of RDG17000386 DMD you can see that there is a period. 在RDG17000386 DMD的行上你可以看到有一段时间。 The period is not supposed to be there and needs to be replaced or removed from the file. 期间不应该在那里,需要从文件中替换或删除。

In my current code I"m searching each line that start with "RDG" and it works find, but I want to limit the search with only the lines that include "DMD" within the line and I've tried changing the RDG to DMD, which didn't work because the line doesn't start with DMD. I'm not entirely sure how to remove or replace the period from the file. Here is what my code looks like so far. 在我当前的代码中,我“搜索以”RDG“开头的每一行并且它可以找到,但我想限制搜索只包含行中包含”DMD“的行,并且我尝试将RDG更改为DMD ,这不起作用,因为该行不以DMD开头。我不完全确定如何从文件中删除或替换句点。这是我的代码到目前为止的样子。

 import java.io.*;

 public class ReadLineAndReplace {

public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader("FilePath"));
    StringBuilder sb = new StringBuilder();
    String line = "";

    while ((line = br.readLine()) != null) {

        if (line.startsWith("RDG")) {
        //assuming the replace would be inserted here   
            System.out.println(line);       
        }
    }
}
}

Use. 使用。 matches() with a regular expression matches()与正则表达式

line.matches("^RDG.*DMD.*")

to replace the dot with a zero 用零替换点

if (line.matches("^RDG.*DMD.*")) {
    line = line.replace('.', '0')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM