CodexBloom - Programming Q&A Platform

Regex for Matching Custom File Path Patterns in Node.js - Handling Special Characters

👀 Views: 3 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-21
regex node.js validation Node.js

I'm following best practices but I've been struggling with this for a few days now and could really use some help. I'm following best practices but I'm trying to figure out I'm trying to use regex in a Node.js application to validate and extract specific file path patterns that include special characters like spaces, dashes, and underscores. My objective is to match paths that follow a format such as `/base/path/file-name_123.txt`. However, I'm working with issues with paths that contain spaces or various combinations of special characters. My current regex pattern is: ```javascript const regex = /^\/base\/path\/([a-zA-Z0-9_-]+(?:\s[a-zA-Z0-9_-]+)*)\.txt$/; ``` When I test it with the following paths: - `/base/path/file-name_123.txt` (valid) - `/base/path/file name 123.txt` (invalid) - `/base/path/file-name.txt` (valid) - `/base/path/file-name-!@#.txt` (invalid) I'm receiving `null` matches for the paths containing spaces and certain special characters. I expected the second path to pass but it fails because the regex does not consider spaces between the valid characters. What modifications can I make to the regex to correctly handle spaces and other allowed special characters without compromising the overall pattern? I've tried several variations, including using `\s*` but it seems to allow too many unexpected matches. I also considered using character classes but I'm unsure how to properly include special characters without making the regex overly complex or performance-heavy. Any advice on best practices for this kind of validation would be greatly appreciated! The project is a CLI tool built with Node.Js. I'd love to hear your thoughts on this. Could someone point me to the right documentation? My development environment is Ubuntu 22.04. Any ideas how to fix this? Any feedback is welcome! I'm working with Node.Js in a Docker container on Ubuntu 20.04. Any feedback is welcome!