Reputation: 11
I'm trying to develop a Java program that matches syslog messages.
The pattern is like this:
"%FACILITY-[SUBFACILITY-]SEVERITY-MNEMONIC: description"
At first I did this regex and it worked for some messages:
(%[a-zA-Z_-]+-[0-6]-[a-zA-Z_-]+[^\r\t\n]+)
Now I need to match only the part before the ":" (i.e, %FACILITY-[SUBFACILITY-]SEVERITY-MNEMONIC) so I'm doing the following, which does not work:
(%[a-zA-Z_-]+-[0-6]-[a-zA-Z_-]+)
I've found some online test pages and the surprising thing is that on the first one the string matches, but not the second (this one is for Java code).
http://www.regexr.com/ -> Match
http://www.regexplanet.com/advanced/java/index.html -> Does not match
This are the strings I'm trying to match:
%HA-REDCON-4-FAILOVER_REQUEST[0x767443be74] Record Reboot History, reboot cause = 0x4000004, descr = Cause: Initiating switch-over.
%ROUTING-FIB-3-ASSERT
error message may occur when doing a RCC check.
Anyone has any idea about this? What am I missing?
Thanks in advance.
Upvotes: 1
Views: 724
Reputation: 626738
To match everything before :
, use ^[^:]+
regex.
See demo (it will work with Java, too, with find()
).
The matches()
in Java just must match the whole string, that is why regexplanet.com says there is no match (but find()
shows success).
If you want to use matches()
, you need to extend the regex to the string end, and only grab the first capturing group: ([^:]+):.*
.
Here is a link to a sample program showing how to capture multiple matches.
String str = "%ROUTING-FIB-3-ASSERT more words here\n%HA-REDCON-4-FAILOVER_REQUEST[0x767443be74] Record Reboot History, reboot cause = 0x4000004, descr = Cause: Initiating switch-over.";
String rx = "(?i)(%[a-z_-]+-[0-6]-[a-z_-]+)";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
System.out.println(m.group(0));
}
Upvotes: 1