import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?P<remoteAdd>[0-9.]+) - (?P<remoteUser>[a-zA-z]+) \\[(?P<timestamp>[^\\]]+)] \"(?P<request>[^\"]+)\" (?P<status>[0-9]+) (?P<bodyBytesSent>[0-9]+) \"(?P<httpReferer>[^\"]+)\" \"(?P<httpUserAgent>[^\"]+)\"";
final String string = "----NGINX----\n\n\n\n"
+ "127.0.0.1 - dbmanager [20/Nov/2017:18:52:17 +0000] \"GET / HTTP/1.1\" 401 188 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0\"\n\n\n\n"
+ " '$remote_addr - $remote_user [$time_local] \"$request\" '\n"
+ " '$status $body_bytes_sent \"$http_referer\" '\n"
+ " '\"$http_user_agent\" \"$http_x_forwarded_for\"'";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (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