FranceMadrid
FranceMadrid

Reputation: 95

Python - How to take arbitrary string in path to a file via regex

I have a path that I have assigned to a string:

string = 'pathos/llb_cube/uni/ToolSub.pm'

However the 'llb' prefix can be different string for each computer and I need to assign it to an arbitrary value that will read whatever the user's computer has set for this specific directory such as:

string = 'pathos/*_cube/uni/ToolSub.pm'

I cannot figure out what function or regex to use for this however.

Upvotes: 0

Views: 101

Answers (1)

N Chauhan
N Chauhan

Reputation: 3515

You can use the dot . to mean 'any character':

string = r'pathos/.*_cube/uni/ToolSub\.pm'
  • I escaped the dot at the end of the string.

  • The * asterisk denotes 0 or more repetitions.

  • I used a raw string literal: r'...' so that I can write backslashes without having to escape them.

If you need a certain number of characters use .{x}. Now you can use regex to match your paths

for path in path_list:
    match = re.match(string, path)
    if match:
        print(match.group(0))

Upvotes: 1

Related Questions