PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 6, 2022

[FIXED] How can I catch the following groups with a regex?

 November 06, 2022     python, python-re, regex, regex-group     No comments   

Issue

Hello I have the following two strings

txt = '/path/to/photo/file.jpg'
txt = '/path/to/photo/file_crXXX.jpg'

in the second string, XXX is a long variable path with information in the name because that is processed.

I want to extract the name 'file' in both path

In order to this, I tried the following code

re.search(".*/(.*)\.jpg", txt).group(1)
re.search(".*/(.*)_cr.*", txt).group(1)

But when I try to combine in one expression with the following code

re.search(".*/(.*)(_cr.*)|(\.jpg)*", txt).group(1)
re.search(".*/(.*)(\.jpg)|(_cr.*)", txt).group(1)

Doesn't work properly, so how can I do this?

Thanks


Solution

The problem was that you had captured a group that should not need to be captured, but the .*/(.*)(\.jpg)|(_cr.*) was closer to the answer. Please use this regex to capture only the filename or its prefix.

([^/]*?)(?:\.jpg|_cr.*)$

Also, see the regex demo

import re

paths = ["/path/to/photo/file.jpg", "/path/to/photo/file_crXXX.jpg"]
for path in paths:
    print(re.search(r"([^/]*?)(?:\.jpg|_cr.*)$", path).group(1))


Answered By - Artyom Vancyan
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing