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 java.util.regex.Pattern;
20
21 import org.apache.logging.log4j.Logger;
22 import org.apache.logging.log4j.core.config.plugins.Plugin;
23 import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
24 import org.apache.logging.log4j.core.config.plugins.PluginFactory;
25 import org.apache.logging.log4j.status.StatusLogger;
26
27
28
29
30 @Plugin(name = "replace", category = "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(final Pattern pattern, final String substitution) {
46 this.pattern = pattern;
47 this.substitution = substitution;
48 }
49
50
51
52
53
54
55 public String format(final 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(
72 @PluginAttribute("regex") final Pattern regex,
73 @PluginAttribute("replacement") final String replacement) {
74 if (regex == null) {
75 LOGGER.error("A regular expression is required for replacement");
76 return null;
77 }
78 if (replacement == null) {
79 LOGGER.error("A replacement string is required to perform replacement");
80 }
81
82 return new RegexReplacement(regex, replacement);
83 }
84
85 }