我认为您正在寻找的正则表达式是:
String regex = "([^\\[:/]+).*";
.*
表示匹配 0 个或多个任意字符。在点星前面放置一对括号().*
会创建一个可以从 Matcher 中选择的组。因为它是第一组括号,所以它被组号 1 引用。括号内是一个表达式,它匹配一个或多个[^]+
包含 OP 中指定的字符的否定字符类,特别是“[”、“:” , 和“/”字符。
这是一个测试结果的示例应用程序:
package com.stackexchange.stackoverflow;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Question19370191 {
public static void main(String[] args) {
String regex = "([^\\[:/]+).*";
Pattern pattern = Pattern.compile(regex);
List<String> lines = new ArrayList<>();
lines.add("2013-10-14T22:05:29+00:00 hostname sshd[6359]: Connection closed by 192.168.1.10");
lines.add("2013-10-14T22:05:29+00:00 hostname sshd:3322 Connection closed by 192.168.1.10");
lines.add("2013-10-14T22:05:29+00:00 hostname sshd/6359 Connection closed by 192.168.1.10");
lines.add("2013-10-14T22:05:29+00:00 hostname sshd Connection closed by 192.168.1.10");
lines.add("2013-10-14T22:05:29+00:00 hostname SSHD[1133] Connection closed by 192.168.1.10");
lines.add("2013-10-14T22:05:29+00:00 hostname SSH.D[6359]: Connection closed by 192.168.1.10");
for(String line : lines) {
String field = line.split("\\s")[2];
String extraction = "";
Matcher matcher = pattern.matcher(field);
if(matcher.matches()) {
extraction = matcher.group(1);
}
System.out.println(String.format("Field \"%-12s\" Extraction \"%s\"", field, extraction));
}
}
}
它输出以下内容:
Field "sshd[6359]: " Extraction "sshd"
Field "sshd:3322 " Extraction "sshd"
Field "sshd/6359 " Extraction "sshd"
Field "sshd " Extraction "sshd"
Field "SSHD[1133] " Extraction "SSHD"
Field "SSH.D[6359]:" Extraction "SSH.D"