Python Forum
Python regex with negative set of characters multiline
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python regex with negative set of characters multiline
#1
Hi,

I have following text stored as a string:

Output:
final class myClass1 { const APPLICATION1 = 1; const APPLICATION2 = 2; } final class myClass2 { const APPLICATION3 = 3; const APPLICATION4 = 4; } final class myClass3 { const APPLICATION5 = 5; const APPLICATION6 = 6; }
I am trying to search the middle block (myClass2), but this pattern does not work:

block = re.search(r'final\sclass\smyClass2\s{([ˆ}]+)}', text, re.DOTALL)
while the next one matches everything up until the very last curly bracket:

block = re.search(r'final\sclass\smyClass2\s{(.+)}', text, re.DOTALL)
Apparently the problem is with the [ˆ}]+ section of the pattern.

Why does it not work as expected - to match any character except of ending curly bracket??
Reply
#2
Something like this.
>>> import re
>>> 
>>> r = re.search(r"myClass2\s{(.*?)}", data, re.MULTILINE | re.DOTALL)
>>> print(r.group(1).strip())
Output:
const APPLICATION3 = 3; const APPLICATION4 = 4;
Reply
#3
Ah, damn! the greedy and non-greedy quantifiers, I totally forgot about them.
Thanks a lot for the tip and reminder, it works now as expected ;-)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  cmath.rect accepts a negative modulus JMB 2 328 Jan-17-2024, 08:00 PM
Last Post: JMB
  capturing multiline output for number of parameters jss 3 809 Sep-01-2023, 05:42 PM
Last Post: jss
  Python Regex quest 2 2,325 Sep-22-2022, 03:15 AM
Last Post: quest
  How to do bar graph with positive and negative values different colors? Mark17 1 5,124 Jun-10-2022, 07:38 PM
Last Post: Mark17
  is there any tool to convert negative base to int? Skaperen 7 2,396 May-27-2022, 07:30 AM
Last Post: Gribouillis
  python regex: get rid of double dot wardancer84 4 2,358 Sep-09-2021, 03:03 PM
Last Post: wardancer84
  Presenting multiline data into single line aaronbuhu 1 1,802 Aug-05-2021, 10:57 AM
Last Post: jamesaarr
  Regex not finding all unicode characters tantony 3 2,279 Jul-13-2021, 09:11 PM
Last Post: tantony
  Using Regex Expression With Isin in Python eddywinch82 0 2,283 Apr-04-2021, 06:25 PM
Last Post: eddywinch82
  Extract continuous numeric characters from a string in Python Robotguy 2 2,632 Jan-16-2021, 12:44 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020