0

How to get regex to get the value after name = in a file, and replace it. I have a file called: 'myfile.txt'.

public static void main(String[] args)
    File TextFile = new File("C:\\text.txt");
    if (TextFile.exists()) {
        try {
            ReplaceWordInFile(TextFile, "haical", "arnanda");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private static void ReplaceWordInFile(File MyFile, String OldText, String NewText)
        throws IOException {

    File tempFile = File.createTempFile("filetemp", ".tmp");
    FileWriter fw = new FileWriter(tempFile);

    Reader fr = new FileReader(MyFile);
    BufferedReader br = new BufferedReader(fr);

    while (br.ready()) {
        fw.write(br.readLine().replaceAll(OldText, NewText) + "\n");
    }

    fw.close();
    br.close();
    fr.close();
    tempFile.renameTo(MyFile);
}

Contents of the file C:\text.txt is:

name = haical
address = Michigan 48309, Amerika Serikat
age = 19
gender = male
activity = school
hoby = hiking, travel

If I run the program above in the first line, name = haical will change to name = arnanda.

My problem is that the value from name isn't 'haical' but another value, so I want to get the value after name = blablabla.

Furthermore, sometimes the statement name = haical won't keep it's number of spaces & changes its position.

Example of the contents of the output at a later time is:

address = Michigan 48309, Amerika Serikat
name   =    haical  
age = 19
gender = male
activity = school
hoby = hiking, travel

So it's not always on the first line and some spaces after the = , but it will always be on line starting with name =.

Thanks in advance.

1 Answer 1

1

use

....replaceAll("^name\\s*=\\s*" + YourNameVariableToReplace + "\\s*$", "name="+YourNameVariableToInsert)

to replace the string. Maybe you need to escape the Name First, if he might contain Regex-Control-Chars.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi dognose, thank you very much, your regex success, i give you vote and true answer. thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.