import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(^\\w{3}\\s+\\d+\\s\\d+:\\d+:\\d+)\\s?:\\s?(\\w+?)\\s+:.*";
final String string = "Aug 7 14:14:43 : user1 : TTY=pts/53 ; PWD=/path2 ;\n"
+ " USER=root ; COMMAND=/path/to/cmd1\n"
+ "Aug 7 14:14:49 : user2 : TTY=pts/53 ; PWD=/usr/home ;\n"
+ " USER=root ; COMMAND=./myscript.sh -m name -o SCHEDULER\n"
+ "Aug 7 14:15:14 : user3 : TTY=pts/34 ;\n"
+ " PWD=/path ; USER=root ;\n"
+ " COMMAND=/usr/bin/egrep ^[a-z]*\n"
+ " /filename/toto1234\n"
+ "Aug 7 14:15:37 : user4 : TTY=unknown ; PWD=/opt/nagios ; USER=root ;\n"
+ " COMMAND=/path/to/less\n"
+ " /var/opt/otherfile\n"
+ "Aug 7 14:16:04 : user4 : TTY=pts/34 ;\n"
+ " PWD=/usr/local/bin/script ; USER=root ;\n"
+ " COMMAND=/usr/bin/egrep ^[a-z]*\n"
+ " /user/local/sbin/tata\n";
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