Reputation: 425
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
Reputation: 200158
It seems like you are on a good path. I would however suggest several things:
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
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