Dzmitry Dzmitry - 2 months ago 11
Python Question

regex greedy match ends with character or end of string

I have two strings:

1) "Created Account Owner Sharing Rule test1"

2) "Updated Account Owner Sharing Rule test3: Changed CaseAccessLevel from Read/Write to Read Only"

As result of regex matching I want to see:

1) Created Account Owner Sharing Rule test1

2) Updated Account Owner Sharing Rule test3

divided into 4 groups:

1) (Created) (Account) (Owner Sharing Rule) (test1)

2) (Updated) (Account) (Owner Sharing Rule) (test3)

For this purposes I tried use the next python regex:

'^(?P<action>^[^\s]+)\s(?P<target_object_label>.+)\s(?P<object_type>Owner\sSharing\sRule)\s(?P<object_label>.+)(?=:|$)


but for the second string 4th group looks like 'test3: Changed CaseAccessLevel from Read/Write to Read Only'.

Essentially regex should stop either in the end of line or before ':' character but greedy match doesn't allow to do this.

Thanks in advance for the answers,

Dzmitry

Jan Jan
Answer

You could do:

^(?P<action>\S+)\ 
(?P<target_object_label>.+)\s
(?P<object_type>Owner\ Sharing\ Rule)\s
(?P<object_label>[^:\n]+)               # stop before : or newline

See a demo on regex101.com (mind the different modifiers!).

Comments