我有文件file1,file2包含以下内容:
[2017-02-01 10:00:00 start running [error:yes] [doing:no] [finish:] [remind:] [alarmno:123456789] [logno:123456789] [ref:-1:2:-1:-1:-1] [type:2:big issues happen] [flag:0:]]<-此行1
[2017-02-01 10:00:00 start running [error:yes] [doing:no] [finish:] [remind:] [alarmno:123456789] [logno:123456789] [ref:-1:2:-1:-1:-1] [type:2:big issues happen] [flag:0:]]
第2行:除日期,类型,登录号和警报号外,同一行1有时包含+或-号。…其他行我已经将所有这些行读到字符串列表myLines。(请注意:file1的内容将是myLines的第一个元素,以 逗号 分隔,而myLines 的第二个元素将是file2的内容,以逗号分隔,依此类推。例如,这是myLines列表的第一个元素:
myLines
[2017-02-01 10:00:00 start running [error:yes] [doing:no] [finish:] [remind:] [alarmno:123456789] [logno:123456789] [ref:-1:2:-1:-1:-1] [type:2:big issues happen] [flag:0:], 2017-02-01 10:00:00 start running [error:yes] [doing:no] [finish:] [remind:] [alarmno:123456789] [logno:123456789] [ref:-1:2:-1:-1:-1] [type:2:big issues happen] [flag:0:]]
<-–这是myLines的第一个元素列出其file1的内容。如果文件包含一行,则意味着myLines列表的第一个元素将仅包含该行且不用逗号分隔。我只想要
这是我尝试的:
String regex = "\\d{2}:\\d{2}:\\d{2}\\s+\\w*\\s+\\w*\\s+\\[\\w*:\\w*]\\s+\\[\\w*:\\]\\s+\\[\\w*:\\]\\s+\\[\\w*:\\]"; String s=null; for(int i=0; i<myLines.size(); i++) { s = myLines.get(i).replaceAll(regex," "); }
但是结果是日期和Alarmno:12345 …以及其他行内容。我什至试图重复这种表达,但对我没有帮助。有什么方法可以在Java中实现吗?
您可以使用
^\[?(\d[\d-]+).*?\[alarmno:(\w*)].*?\[logno:(\w*)].*?\[type:\w*:([^\]]*)]
参见正则表达式演示
详细资料 :
^
\[?
[
(\d[\d-]+)
-
.*?
\[alarmno:
[alarmno:
(\w*)
]
\[logno:
[logno:
\[type:
[type:
\w*
:
([^\]]*)
Java演示:
String s = "[2017-08-17 08:00:00 Comming in [Contact:NO] [REF:] [REF2:] [REF3:] [Name:+AA] [Fam:aa] [TEMP:-2:0:-2:0:-2] [Resident:9:free] [end:0:]"; Pattern pat = Pattern.compile("^\\[*(\\d[\\d: -]+\\d).*?\\[Name:([^]]*)].*?\\[Fam:(\\w*)].*?\\[Resident:\\w*:([^]]*)]"); Matcher matcher = pat.matcher(s); if (matcher.find()){ System.out.println("Date: " + matcher.group(1)); System.out.println("Name: " + matcher.group(2)); System.out.println("Fam: " + matcher.group(3)); System.out.println("Resident: " + matcher.group(4)); }
输出:
Date: 2017-08-17 08:00:00 Name: +AA Fam: aa Resident: free