regexlinuxstring

Regex to tell if a string contains a linux file path or if a linux file path as part of a string


I am writing a regular expression that will be used to see if a string contains a file path for a linux system as the whole string or a file path for a linux system as only part of the string. So basically when a file path is the whole string I want a match, but when the file path is just part of the string I don't want a match. For example I would want the following string to tell me there is a match

/home/user/Documents/foo.log

and this string not be a match

/home/user/Documents/foo.log was written

as well as this string not be a match

the file /home/user/Documents/foo.log was written

The only thing I have been able to come up with so far is this,

^(\/*)

Which only says ok you have a slash followed by a character but am not sure what else to use to get the regular expression to work as I would like it to. Does anyone have any input on how to expand upon my regular expression to get it to match what I am looking to do?

EDIT

Spaces are not part of allowed file names as part of the naming convention. Yes a user could put a space since it is a linux system, however that would then be a user error.


Solution

  • Regex for full Linux filesystem paths with spaces can be:

    ^(/[^/ ]*)+/?$
    

    RegEx Demo

    RegEx Details: