我不是正则表达式方面的专家,想知道是否有人可以帮助我:
我想分割以下字符串:
04/16/2015 14:01:58.819 (27327) [ERR] [SYSTEM CALL] SOCKET BIND port=4664: Address already in use [tsocket:820]
分为以下 5 个标记:
04/16/2015 14:01:58.819
27327
ERR
SYSTEM CALL
SOCKET BIND port=4664: Address already in use [tsocket:820]
下面的 Java 代码使用正则表达式 [()\\[\\]]
帮我实现了这一点,但它效率低下!
List<String> splitline(String line) {
List<String> tokens = new ArrayList<>();
int numToks = 0;
line = line.trim();
//Question 1: Change regular expression to remove white-space-only tokens!!
String[] rawToks = line.split("[()\\[\\]]");
for (String t : rawToks) {
String token = t.trim();
if (!token.isEmpty()) {
if (numToks < 4) {
tokens.add(token);
}
numToks++;
}
}
//Question 2: Can the regular express be enhanced to eliminate this step?
//In case the last required token contains () or [] then there will be more than 5 tokens,
//so split by the 4th token (with [] around it) & use the 2nd token from the result
if (numToks > 4) {
tokens.add(line.split("\\[" + tokens.get(3) + "\\]")[1].trim());
}
return tokens;
}
有人知道上面代码中嵌入的两个问题的答案吗?
编辑:
以下代码回答了上述两个问题,感谢下面接受的答案!
List<String> splitline(String line) {
return Arrays.asList(line.trim().split("[)\\]]?\\s+[(\\[]|]\\s+", 5));
}
最佳答案
\\s*[()\\[\\]]\\s*
您可以简单地以此进行拆分,并使用 java 中提供的 not None
或 notempty
删除空的拆分部分。请参阅演示。
关于java - 用于忽略纯空白标记的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30637509/