How to get the name of a directory by regex?

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To get the name of a directory using regex in Python, you can use the re module to match and extract the desired directory name. Here's an example:

python
import re

# Input directory path
directory_path = "/path/to/directory"

# Regex pattern to match directory name
regex_pattern = r"/([^/]+)$"

# Extract directory name using regex
match = re.search(regex_pattern, directory_path)
if match:
directory_name = match.group(1)
print("Directory name:", directory_name)
else:
print("No match found")

In this example, the regex_pattern uses the r"/([^/]+)$" pattern to match the last directory in the given path. The ([^/]+) part captures one or more characters that are not a forward slash, and the $ matches the end of the string.

The re.search() function is used to search for a match in the directory_path using the regex_pattern. If a match is found, the captured group (i.e., the directory name) is extracted using match.group(1).

Make sure to adjust the regex pattern to fit your specific requirements.