Regex to detect filesystem path values

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
harsha
Forum Contributor
Posts: 103
Joined: Thu Jul 11, 2002 1:35 am
Location: Bengaluru (Bangalore) > Karnataka > India

Regex to detect filesystem path values

Post by harsha »

I constructed the following regex to detect filesystem path values.
these path values are randomly present in a log file and they are embedded inside single quotes.

some thing like this:
this is the project path: '/usr/share/project/'


Assumptions:

No special chars will be there in the filesystem path that is: (~!@#$%^&*():;''><.,/?)

Code: Select all

\'(\/+[\w-_.\s]{1,255})+\'

comments Please, so that I can optimize further.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

\w can allow "special characters."

And what if the path doesn't start with a slash?
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

I'd suggest

Code: Select all

$path = "~
   /? # optional root
   ([\w.-]+/)* # 0 or more directory names, followed by slash
   ([\w.-]*) # possibly empty filename
~x";
Post Reply