1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.pattern;
18
19 import org.apache.logging.log4j.Logger;
20 import org.apache.logging.log4j.core.config.plugins.Plugin;
21 import org.apache.logging.log4j.core.config.plugins.PluginAttr;
22 import org.apache.logging.log4j.core.config.plugins.PluginFactory;
23 import org.apache.logging.log4j.status.StatusLogger;
24
25 import java.util.regex.Pattern;
26
27
28
29
30 @Plugin(name = "replace", type = "Core", printObject = true)
31 public final class RegexReplacement {
32
33 private static final Logger LOGGER = StatusLogger.getLogger();
34
35 private final Pattern pattern;
36
37 private final String substitution;
38
39
40
41
42
43
44
45 private RegexReplacement(Pattern pattern, String substitution) {
46 this.pattern = pattern;
47 this.substitution = substitution;
48 }
49
50
51
52
53
54
55 public String format(String msg) {
56 return pattern.matcher(msg).replaceAll(substitution);
57 }
58
59 @Override
60 public String toString() {
61 return "replace(regex=" + pattern.pattern() + ", replacement=" + substitution + ")";
62 }
63
64
65
66
67
68
69
70 @PluginFactory
71 public static RegexReplacement createRegexReplacement(@PluginAttr("regex") String regex,
72 @PluginAttr("replacement") String replacement) {
73 if (regex == null) {
74 LOGGER.error("A regular expression is required for replacement");
75 return null;
76 }
77 if (replacement == null) {
78 LOGGER.error("A replacement string is required to perform replacement");
79 }
80 Pattern p = Pattern.compile(regex);
81 return new RegexReplacement(p, replacement);
82 }
83
84 }