开发者

Building Regex Expression

Can you tell me the regex for capturing class name from below line:

[2011-09-14 开发者_如何转开发20:43:31:943 GMT][E08C17F94E8.http-8080-Processor21]com.abc.MyClass] INFO login successful

Here, I need to capture MyClass.

So far, I was able to capture entire com.abc.MyClass using (?i)^(?:[^\[]*\[){3}

But I couldn't capture MyClass.

Any help is much appreciated.

Thanks!


If it's possible for the end (the part that says "login successful") to have brackets, you can use this:

^\[[^]]*\]\[[^]]*\][^]]*\.([^]]+)\].*$

Let's see if I can break this down a little...

^\[[^]]*\] matches the first bracket, all following non-"]" characters, and a closing bracket. This is the [2011-09-14 20:43:31:943 GMT] part.

\[[^]]*\] then matches an opening bracket, all following non-"]" characters, and another closing bracket. This is the [E08C17F94E8.http-8080-Processor21] part.

[^]]*\.([^]]+) then matches all non-"]" characters, followed by a period, followed by one or more non-"]" characters. This is the com.abc.MyClass part. The MyClass part gets matched to the part in parenthesis.

\].*$ matches a closing bracket and the rest of the string. This is the ] INFO login successful part.

So if you replace ^\[[^]]*\]\[[^]]*\][^]]*\.([^]]+)\].*$ with $1 in your example, you're left with MyClass.


If you can assume there are never brackets after that last one, it is pretty simple:

(\w+)\][^]]$

This captures all of the alphanumeric characters directly preceding the last ] in the string.

Note: you don't need to do [^\]] because the spec for PCRE says if the ] is the first in the character list, you don't need to escape it.

EDIT: Since you cannot assume no brackets, here is another one that will work:

\[.+?\]\[.+?\].*?(\w+)\]

This throws away the first two sets of brackets, and grabs the largest chunk of alphanumeric characters before the next bracket. The ? in .+? makes it a non-greedy multiplier, so it will match as few characters as possible, which makes this regex very simple and efficient.

Nothing against daxnitro, but that regex makes me want to give up programming.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜