deb
deb

Reputation: 425

Java replacing in a file regex

I want to put in a file some regex expressions and separated by a semicolon (or something) another expression, i.e.:

orderNumber:* completionStatus;orderNumber:X completionStatus

I will have a log file what will have:

.... orderNumber:123 completionStatus...

and I want them to look like:

.... orderNumber:X completionStatus...

How can I do this in Java?

I've tried creating a Map with (key: the regex, and value: the replacement), reading my log file and for each line try matching the keys but my output looks the same.

FileInputStream fstream = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader( in ));
FileWriter fstreamError = new FileWriter(myFile.replace(".", "Replaced."));
BufferedWriter output = new BufferedWriter(fstreamError);

while ((strFile = br.readLine()) != null) {
    for (String clave: expressions.keySet()) {
        Pattern p = Pattern.compile(clave);
        Matcher m = p.matcher(strFile); // get a matcher object
        strFile = m.replaceAll(expressions.get(clave));
        System.out.println(strFile);
    }
}

Any thoughts on this?

Upvotes: 0

Views: 6026

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200158

It seems like you are on a good path. I would however suggest several things:

  1. Do not compile the regex every time. You should have them all precomplied and just produce new matchers from them in your loop.
  2. You aren't really using the map as a map, but as a collection of pairs. You could easily make a small class RegexReplacement and then just have a List<RegexReplacement> that you iterate over in the loop.

class RegexReplacement { 
  final Pattern regex;
  final String replacement;
  RegexReplacement(String regex, String replacement) {
    this.regex = Pattern.compile(regex);
    this.replacement = replacement;
  }
  String replace(String in) { return regex.matcher(in).replaceAll(replacement); }
}

Upvotes: 1

Andr&#233;s Oviedo
Andr&#233;s Oviedo

Reputation: 1428

is this what you are looking for?

import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexpTests {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String text = "orderNumber:123 completionStatus";
    String regexp = "(.*):\\d+ (.*)";
    String msgFormat = "{0}:X {1}";

    Pattern p = Pattern.compile(regexp);
    Matcher m = p.matcher(text);

    MessageFormat mf = new MessageFormat(msgFormat);
    if (m.find()) {
        String[] captures = new String[m.groupCount()];
        for (int i = 0; i < m.groupCount(); i++) {
            captures[i] = m.group(i + 1);
        }
        System.out.println(mf.format(msgFormat, captures));
    }

}

}

Upvotes: 1

Related Questions