Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex works online but not in code

This regex pattern: ^.+\'(.+.png) works in online editors but not in python code. I saw other posts having the same issue. I tried applying those;

  • Adding an extra escape slash

  • Prepending start quote with r

the regex should match starting at single quote untill it hits .png.

For example:

With this string Executing identify -format %k 'testcases/art/test_files/video_images/single-[snk1=640x480p59.9]-[src1=720x480i59.9].png'

I want: testcases/art/test_files/video_images/single-[snk1=640x480p59.9]-[src1=720x480i59.9].png

I tried (not in chronological order):

result = re.findall("^.+\\'(.+\\.png)", self.stream.getvalue()) # I also tried prepending all of these with r
result = re.findall("^.+\'(.+.png)", self.stream.getvalue())
result = re.findall("^.+'(.+.png)", self.stream.getvalue())
result = re.findall("^.+'(.+.png)", str(self.stream.getvalue()))
result = re.findall("\^.+'(.+.png)\", self.stream.getvalue())

Edit: I also tried using re.match() and re.search()

Update:

Probably where I'm getting the string from is responsible cStringIO.StringO.getvalue() which is this part in code self.stream.getvalue(). This is code I have not written. How can I use regex on this?

like image 676
Bas Velden Avatar asked May 18 '26 02:05

Bas Velden


1 Answers

You need to cast the output of self.stream.getvalue() to a string and also throw away the ^.+ part of the pattern as re.findall searches for all matches anywhere inside the input string.

Use

results = re.findall(r"'([^']+\.png)", str(self.stream.getvalue()))

Also, mind escaping dots that are literal . chars in the pattern.

Pattern details

  • ' - a single quote
  • ([^']+\.png) - Capturing group 1:
    • [^']+ - 1+ chars other than '
    • \.png - .png substring.
like image 78
Wiktor Stribiżew Avatar answered May 20 '26 15:05

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!