stackmonkey
stackmonkey

Reputation: 115

Positive lookbehind regex obvious maximum length

So I have been experimenting with regex in order to parse the following strings:

INFO: Device 6: Time 20.11.2015 06:28:00 - [Script] FunFehlerButton: Execute [0031 text]    
and    
INFO: Device 0: Time 09.12.2015 03:51:44 - [Replication] FunFehlerButton: Execute    
and    
INFO: Device 6: Time 20.11.2015 06:28:00 - FunFehlerButton: Execute

The regex I tried to use are:

(?<=\\d{1,2}:\\d{2}:\\d{2} - ).*    

and

(?<=\\[\\w*\\]).*    

of which the first one runs correctly and the second one lands in a expcetion.

My goal is to get the text "FunFehlerButton: Execute ...".

I hope someone can hint me in the right direction.

Upvotes: 1

Views: 600

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89629

Java supports variable length lookbehind only if the size is limited and the subpattern in the lookbehind isn't too complicated.

In short, you can't write:

(?<=\\[\\w*\\]).*

But you can write:

(?<=\\[\\w{0,1000}\\]).*

However something like:

(?<=\\[(?:\\w{0,2}){0,500}\\w?\\]).*

doesn't work since the max length isn't obvious.

Upvotes: 1

anubhava
anubhava

Reputation: 785991

Java doesn't support variable length expression in lookbehind.

You can instead use this regex:

String re = "(?:\\d{2}:\\d{2}:\\d{2} - (?:\\[[^\\]]*\\] )?)([\\w: -]+)";

And use captured group #1

RegEx Demo

Upvotes: 1

Related Questions