Python regular expression to match string excluding word

I have a problem with creating a regex, and I searched for 2 days around Google, stack overflow and other documents ...

I have the following lines:

2015-07-08 12:49:07.183852|INFO    |VirtualServerBase|  3| client disconnected 'Ròem'(id:6336) reason 'invokerid=20 invokername=Alphonse invokeruid=loremipsum2= reasonmsg=test'
2015-07-08 11:59:23.178055|INFO    |VirtualServerBase|  3| client disconnected 'Trakiyen'(id:20460) reason 'invokerid=0 invokername=server reasonmsg=idle time exceeded'
2015-07-08 12:40:50.591450|INFO    |VirtualServerBase|  3| client disconnected 'kalash'(id:20464) reason 'invokerid=136 invokername=Charles invokeruid=loremipsum= reasonmsg=Aller, Bisous! bantime=0
2015-07-08 00:23:03.235312|INFO    |VirtualServerBase|  3| client disconnected 'Brigata FTW'(id:20451) reason 'invokerid=103 invokername=Bob invokeruid=loremipsum3= reasonmsg=En vous souhaitant une bonne soirée <3 bantime=28800'

I want to combine only the first line, following these conditions:

  • No line with invokername=server
  • No line with bantime

In this case, the result should match only the first line with the following regular expression:

.*2015-07-08.*client disconnected.*invokername=[^server].*[^bantime=].*

I write only one regular expression, but I have tried many, many different things (s ?!, etc.). I read a lot of topics about Stack Overflow exception, but couldn't find a solution. Hope someone helps me.

+4
source share
3 answers

You can get your string with

(?m)^(?!.*\b(?:invokername=server|bantime)\b).*2015-07-08.*client disconnected.*invokername=.*$

Watch the demo

EXPLANATION

  • (?m) - , ^ $ .
  • ^ -
  • (?!.*\b(?:invokername=server|bantime)\b) - , , invokername=server bantime
  • .*2015-07-08.*client disconnected.*invokername=.* - , 2015-07-08, client disconnected, invokername=, - ( ).
  • $ -

* , :

(?m)^(?!.*\b(?:invokername=server|bantime)\b).*$

, "" .

+3

, [^...] (?!...). - , - .

, , :

.*?2015-07-08.*?client disconnected.*?(invokername=(?!server))((?!.*?bantime=).*)

: , : @stribizhev , :

(?m)^(?!.*\b(?:invokername=server|bantime)\b).*$
+3

Along with @llogiq's answer explaining the difference between a negative character class and a negative appearance, you can also only use the following regular expression, using a negative look ahead :

^((?!bantime|(?:invokername=server)).)*$

See the demo https://regex101.com/r/hI5dR0/1

>>> re.search(r'^((?!bantime|(invokername=server)).)*$',s,re.M).group()
"015-07-08 12:49:07.183852|INFO    |VirtualServerBase|  3| client disconnected 'R\xc3\xb2em'(id:6336) reason 'invokerid=20 invokername=Alphonse invokeruid=loremipsum2= reasonmsg=test'"
+2
source

All Articles