import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = " ^(?P<timestamp>\\d{4}/\\d{2}/\\d{2}\\ \\d{2}:\\d{2}:\\d{2})\n"
+ " \\ \\[(?P<severity>emerg|alert|crit|error|warn|notice|info)\\]\n"
+ " \\ (?P<process_id>\\d+)\n"
+ " \\#(?P<thread_id>\\d+):\n"
+ " \\ \\*(?P<connection_id>\\d+)\n"
+ " \\ (?P<error>.+?)\n"
+ " (?:\\ while\\ (?P<context>.+?))?\n"
+ " ,\\ client:\\ (?P<client_ip>\\d+\\.\\d+\\.\\d+\\.\\d+)\n"
+ " ,\\ server:\\ (?P<server>.+?)\n"
+ " (?:,\\ request:\\ \\\"(?P<request_method>[A-Z]+?)\n"
+ " \\ (?P<request_path>\\/.+?)\n"
+ " \\ (?P<request_protocol>.+?)\\\")?\n"
+ " (?:,\\ upstream:\\ \\\"(?P<upstream>.+?)\\\")?\n"
+ " (?:,\\ host:\\ \\\"(?P<host>.+?)\\\")?\n"
+ " (?:,\\ referrer:\\ \\\"(?P<referrer>.+?)\\\")?\n"
+ " $";
final String string = "2019/07/11 07:19:30 [error] 934#934: *18897816 open() \"/local/nginx/static/ads.txt\" failed (2: No such file or directory), client: 85.195.82.90, server: app.digitale-sammlungen.de, request: \"GET /ads.txt HTTP/1.1\", host: \"app.digitale-sammlungen.de\"";
final Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS | Pattern.DOTALL);
final Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html