简体   繁体   中英

Java Regular expression find and update

I need to add couple of import statements in every file in java project. I have written regular expression to perform this activity.

File1.java
/**********************
*
*History Card
*
***********************/
package com.employee.details;

import java.io.BufferedReader;
import java.io.File;

public class File1
{

// java code
}

File2.java

package com.employee.details;
/**********************
*
*History Card
*
***********************/
import java.io.BufferedReader;
import java.io.File;

public class File1
{

// java code
}

Code to Perform the update:

String regEx = "^package .*;";
String pattern = "\0\n\nimport java.io.FileReader;\nimport java.nio.file.Path;";
textFile.replaceAll(regEx,pattern);

it's not working. whats wrong in my code? please help me

The problem is a) the comment at the beginning of the file, b) the greedy quantifier, and c) the missing variable assignment. Probably a removed package declaration as well. You should be using this code:

String regex = "(package .*?;)";
String replacement = "$1\0\n\nimport java.io.FileReader;\nimport java.nio.file.Path;";
textFile = textFile.replaceFirst(regex, replacement);

Strings in Java (in most languages, in fact) are immutable, and thus you can't change every instance of that string at once without a very large amount of code.

Your problem is the java uses the dollar sign flavour of back references, not the backslash flavour.

In your replacement, \\0 is a nul char (hex zero), not group zero. Change it to $0 :

String pattern = "$0\n\nimport java.io.FileReader;\nimport java.nio.file.Path;";
                  ^----- backslash changed to dollar sign

@RamenChef is almost right except that grouping (ie ( and ) ) is not necessary and backreference (ie \\0 ) too. So next code will work:

String regEx = "^package .*;";
String pattern = "$0\n\nimport java.io.FileReader;\nimport java.nio.file.Path;";
textFile = textFile.replaceAll(regEx,pattern);

Note only difference between your code and this is dollar sign before 0 and assigning of replaceAll result to textFile because String type is immutable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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