← Back to Blog

Regular Expressions for File Renaming: A Practical Guide with Examples

Regular expressions (regex) are one of the most powerful tools for file renaming, enabling complex transformations that would be tedious or impossible with simple find-and-replace. While they may seem intimidating at first, mastering a few key patterns can revolutionize your file management workflow.

This guide focuses on practical, real-world examples that you can immediately apply to your file renaming tasks.

What Are Regular Expressions?

Regular expressions are patterns that describe text. They allow you to:

  • Match: Find specific patterns in filenames
  • Extract: Pull out portions of filenames
  • Transform: Restructure and reformat filenames
  • Validate: Ensure filenames follow certain rules

Think of regex as a sophisticated search-and-replace on steroids.

Basic Regex Concepts

Before diving into examples, let’s understand the fundamental building blocks:

Literal Characters

  • abc matches exactly “abc”
  • 2023 matches “2023”

Special Characters (Metacharacters)

  • . matches any single character
  • * matches 0 or more of the previous character
  • + matches 1 or more of the previous character
  • ? matches 0 or 1 of the previous character
  • ^ matches the start of the string
  • $ matches the end of the string
  • [] matches any character inside brackets
  • () creates a capture group

Character Classes

  • \d matches any digit (0-9)
  • \w matches any word character (letters, digits, underscore)
  • \s matches any whitespace character
  • . matches any character except newline

Quantifiers

  • {3} matches exactly 3 occurrences
  • {3,} matches 3 or more occurrences
  • {3,6} matches 3 to 6 occurrences

Real-World File Renaming Examples

Example 1: Reformatting Dates

Scenario: Convert dates from YYYY-MM-DD to DD-MM-YYYY

Files:

2023-12-25-christmas.jpg
2024-01-01-newyear.jpg
2024-06-15-vacation.jpg

Regex Pattern: ^(\d{4})-(\d{2})-(\d{2})-(.+)$

Replacement: $3-$2-$1-$4

Result:

25-12-2023-christmas.jpg
01-01-2024-newyear.jpg
15-06-2024-vacation.jpg

Explanation:

  • ^ - Start of filename
  • (\d{4}) - Capture 4 digits (year) as group 1
  • - - Literal hyphen
  • (\d{2}) - Capture 2 digits (month) as group 2
  • - - Literal hyphen
  • (\d{2}) - Capture 2 digits (day) as group 3
  • - - Literal hyphen
  • (.+) - Capture rest of filename as group 4
  • $ - End of filename

In the replacement, $3-$2-$1-$4 rearranges the groups in the desired order.


Example 2: Removing Prefixes

Scenario: Remove “IMG_” prefix from camera photos

Files:

IMG_0001.jpg
IMG_0002.jpg
IMG_0123.jpg

Regex Pattern: ^IMG_(.+)$

Replacement: $1

Result:

0001.jpg
0002.jpg
0123.jpg

Explanation:

  • ^IMG_ - Match “IMG_” at the start
  • (.+) - Capture everything else
  • Replace with just the captured group

Example 3: Adding Prefixes Based on Content

Scenario: Add date prefix to files that don’t have one

Files:

vacation-photo.jpg
DSC_0001.jpg
beach-sunset.jpg

Regex Pattern: ^(?!20\d{2})(.+)$

Replacement: 2024-10-$1

Result:

2024-10-vacation-photo.jpg
2024-10-DSC_0001.jpg
2024-10-beach-sunset.jpg

Explanation:

  • ^ - Start of filename
  • (?!20\d{2}) - Negative lookahead: ensure it doesn’t start with a year (20XX)
  • (.+) - Capture the entire filename
  • Replace with date prefix plus original filename

Example 4: Extracting Episode Numbers

Scenario: Extract episode numbers from various formats

Files:

Series.Name.S01E05.720p.mkv
Series.Name.1x05.HDTV.mkv
Series.Name.Episode.05.mp4

Regex Pattern: [Ss]0?(\d+)[Ee]0?(\d+)|(\d+)x0?(\d+)|Episode\.0?(\d+)

Replacement: S01E$1$2$3$4$5

This is more complex but demonstrates matching multiple patterns.


Example 5: Cleaning Up Download Filenames

Scenario: Remove common download artifacts and clean up spacing

Files:

Document_Name_(1)_Final_FINAL_v2.pdf
Another-Document--Copy-(3).pdf
Important_File___Draft.docx

Regex Pattern: [-_]+

Replacement: -

Result:

Document-Name-(1)-Final-FINAL-v2.pdf
Another-Document-Copy-(3).pdf
Important-File-Draft.docx

Explanation:

  • [-_]+ - Match one or more hyphens or underscores
  • Replace with single hyphen

Then apply a second pattern to remove duplicates and drafts:

Pattern: [-_](Copy|\d+|Draft|FINAL)[-_]?

Replacement: -


Example 6: Standardizing Extensions

Scenario: Convert uppercase extensions to lowercase

Files:

photo.JPG
document.PDF
video.MP4

Regex Pattern: \.([A-Z]+)$

Replacement: .$1 (with lowercase flag enabled)

Result:

photo.jpg
document.pdf
video.mp4

Explanation:

  • \. - Match literal dot
  • ([A-Z]+) - Capture uppercase letters
  • $ - End of filename
  • In most tools, you can apply a lowercase transformation to captured groups

Example 7: Inserting Text at Specific Positions

Scenario: Insert “backup-” before the extension

Files:

important-file.doc
data-sheet.xlsx
presentation.pptx

Regex Pattern: ^(.+)\.([^.]+)$

Replacement: $1-backup.$2

Result:

important-file-backup.doc
data-sheet-backup.xlsx
presentation-backup.pptx

Explanation:

  • ^(.+) - Capture filename without extension
  • \. - Literal dot
  • ([^.]+)$ - Capture extension (characters that aren’t dots until end)

Example 8: Padding Numbers with Zeros

Scenario: Pad single-digit numbers with zeros

Files:

file-1.txt
file-2.txt
file-10.txt
file-100.txt

Regex Pattern: -(\d)\.

Replacement: -00$1.

For double digits:

Pattern: -(\d{2})\.

Replacement: -0$1.

Result:

file-001.txt
file-002.txt
file-010.txt
file-100.txt

Example 9: Extracting and Reformatting Metadata

Scenario: Extract resolution from filename and standardize format

Files:

video-1920x1080-hdtv.mp4
video-1280x720-web.mp4
video-3840x2160-4k.mp4

Regex Pattern: ^(.+)-(\d+)x(\d+)-(.+)\.(.+)$

Replacement: $1-[$2x$3]-$4.$5

Result:

video-[1920x1080]-hdtv.mp4
video-[1280x720]-web.mp4
video-[3840x2160]-4k.mp4

Example 10: Removing Brackets and Contents

Scenario: Remove bracketed text from filenames

Files:

Report [Draft].pdf
Document [Internal Use Only].docx
File [v2.3] [final].txt

Regex Pattern: \s*\[.*?\]\s*

Replacement:

Result:

Report.pdf
Document.docx
File.txt

Explanation:

  • \s* - Optional whitespace before bracket
  • \[ - Literal opening bracket
  • .*? - Any characters (non-greedy)
  • \] - Literal closing bracket
  • \s* - Optional whitespace after bracket

Then apply trimming pattern to remove extra spaces:

Pattern: \s{2,}

Replacement:


Advanced Techniques

Conditional Replacements

Use lookaheads and lookbehinds for complex conditional logic:

Positive Lookahead: X(?=Y) matches X only if followed by Y Negative Lookahead: X(?!Y) matches X only if NOT followed by Y Positive Lookbehind: (?<=Y)X matches X only if preceded by Y Negative Lookbehind: (?<!Y)X matches X only if NOT preceded by Y

Example: Match numbers not followed by a letter

Pattern: \d+(?![a-z])

Capture Groups vs. Non-Capturing Groups

Capturing: (pattern) - Saves for later use Non-Capturing: (?:pattern) - Matches but doesn’t save (more efficient)

Example:

Pattern: (?:file|document)-(\d+)

This matches “file-123” or “document-123” but only captures the number.

Greedy vs. Non-Greedy Matching

  • .* - Greedy: matches as much as possible
  • .*? - Non-greedy: matches as little as possible

Example with: <tag>content</tag><tag>more</tag>

  • <tag>.*</tag> matches the entire string (greedy)
  • <tag>.*?</tag> matches each tag pair separately (non-greedy)

Practical Tips for Using Regex in File Renaming

1. Always Test First

Use the preview feature in your renaming tool to verify the pattern works correctly before applying it.

2. Start Simple

Begin with literal matches and add complexity gradually. Test each addition.

3. Escape Special Characters

If you need to match special characters literally, escape them with backslash:

  • .\.
  • *\*
  • (\(
  • [\[

4. Use Online Regex Testers

Websites like regex101.com let you test patterns with explanations.

5. Save Common Patterns

Keep a library of frequently-used regex patterns for quick reuse.

6. Handle Edge Cases

Consider what happens with:

  • Very short filenames
  • Filenames with multiple dots
  • Filenames with special characters
  • Unicode characters

7. Backup Important Files

When working with critical files, create backups before applying regex-based renaming.


Common Regex Patterns Cheat Sheet

Matching Patterns

\d{4}           # Four digits (e.g., year)
\d{1,2}         # One or two digits
[A-Za-z]+       # One or more letters
\w+             # One or more word characters
[^.]            # Any character except dot
^file           # Starts with "file"
\.jpg$          # Ends with ".jpg"

Date Patterns

\d{4}-\d{2}-\d{2}                    # YYYY-MM-DD
\d{2}/\d{2}/\d{4}                    # MM/DD/YYYY
\d{4}\d{2}\d{2}                      # YYYYMMDD
(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) # Month names

File Naming Patterns

^([^.]+)\.([^.]+)$                   # Split filename and extension
IMG_\d{4}                            # Camera photo format
\((\d+)\)                            # Numbered copy (1), (2), etc.
[-_\s]+                              # Multiple separators

Text Cleaning

\s+                                  # Multiple spaces
[^\w\s.-]                            # Non-alphanumeric except space, dot, hyphen
\s*[-_]\s*                           # Separator with optional spaces

Using Regex in Nomio

Nomio supports regex in its Replacing Mode:

  1. Enable Regex: Check the “Use Regular Expression” option
  2. Enter Pattern: Input your regex pattern in the “Find” field
  3. Enter Replacement: Use $1, $2, etc. to reference captured groups
  4. Preview: Check the preview pane to verify results
  5. Apply: Click “Apply” to rename files

Example Workflow

Task: Convert YYYY-MM-DD-description.jpg to description-YYYY-MM-DD.jpg

  1. Select files in Nomio
  2. Switch to Replacing Mode
  3. Enable “Use Regular Expression”
  4. Pattern: ^(\d{4}-\d{2}-\d{2})-(.+)$
  5. Replace: $2-$1
  6. Preview and apply

For even more complex transformations, use Scripting Mode with JavaScript, which gives you full programmatic control:

// JavaScript example in Scripting Mode
const match = filename.match(/^(\d{4})-(\d{2})-(\d{2})-(.+)$/);
if (match) {
  const [, year, month, day, description] = match;
  return `${description}-${year}-${month}-${day}`;
}
return filename;

Common Mistakes to Avoid

1. Forgetting to Escape Special Characters

file.txt (matches “file” + any character + “txt”) ✅ file\.txt (matches literal “file.txt”)

2. Greedy Matching When You Need Non-Greedy

<.*> on <a>text</a> matches the entire string ✅ <.*?> matches just <a> and </a> separately

3. Not Anchoring Patterns

\d{4} might match in the middle of a longer number ✅ ^\d{4}$ ensures exactly 4 digits

4. Forgetting About Case Sensitivity

Use case-insensitive flag or character classes:

  • [Ff]ile matches “File” or “file”
  • Or use case-insensitive mode (varies by tool)

5. Not Testing Edge Cases

Always test with:

  • Shortest possible filename
  • Longest possible filename
  • Filenames with special characters
  • Files that shouldn’t match

Conclusion

Regular expressions unlock powerful file renaming capabilities that would be tedious or impossible with simple text replacement. While the learning curve exists, mastering even a handful of patterns can dramatically improve your file management efficiency.

Key takeaways:

  1. Start Simple: Begin with basic patterns and add complexity as needed
  2. Test Thoroughly: Always preview before applying to ensure correct results
  3. Build a Library: Save frequently-used patterns for quick reuse
  4. Use Tools Wisely: Choose tools like Nomio that provide clear previews
  5. Practice: The more you use regex, the more intuitive it becomes

With Nomio’s regex support in Replacing Mode and full JavaScript power in Scripting Mode, you have all the tools you need to tackle any file renaming challenge—from simple standardization to complex transformations.

Ready to put your regex skills to work? Try Nomio today and experience the power of pattern-based file renaming without any installation or setup required.