(? <Name> pattern)
.Matcher # group (String name)
.In order to make the parts versatile, regular expressions may be sent out to property files.
For example, if you want to extract a log of the form time [thread name] error level class name --message
for each element, you can write as follows.
log.pattern=(.+?) \[(.+?)\](ERROR|INFO|DEBUG) (.*?) - (.*?)
String log = "22:22:50.324 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []";
String patternString = getProperty("log.pattern");
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(log);
if (matcher.matches()) {
String time = matcher.group(1);
String thread = matcher.group(2);
String level = matcher.group(3);
String className = matcher.group(4);
String message = matcher.group(5);
・ ・ ・
}
At first glance it looks versatile, but this technique has major weaknesses. That is, the order of the groups cannot be changed. This is because the Java code specifies the order of the groups to retrieve the values of the groups.
For example, the code breaks as soon as the thread name and error level are swapped as shown below. I intended to make it general purpose.
22:22:50.324 DEBUG [main] org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
Starting with Java 1.7, "Regular expression groups with named forward references" are available.
You can name a group of regular expressions by writing (? <Name> pattern)
.
Let's apply it to the regular expression.
log.pattern=(?<time>.+?) \[(?<thread>.+?)\](?<level>ERROR|INFO|DEBUG) (?<className>.*?) - (?<message>.*?)
To retrieve this, use Matcher # group (String name)
String time = matcher.group("time");
String thread = matcher.group("thread");
String level = matcher.group("level");
String className = matcher.group("className");
String message = matcher.group("message");
Since it is acquired by name, even if the thread name and error level order are changed, it can be handled by simply changing the regular expression.
log.pattern=(?<time>.+?) (?<level>ERROR|INFO|DEBUG) \[(?<thread>.+?)\](?<className>.*?) - (?<message>.*?)
It's a simple but convenient function.
Recommended Posts