Search code examples
matlab

Matlab RegEx for specific string pattern


I'm working with the following file addresses format:

/A/B/C/D/foo/bar

I want to come up with a regular expression in Matlab that will return the last word in the adress. In this case I want the word "bar". What would be the regular expression?


Solution

  • If you're just trying to get the file name from the full file path, you can use fileparts rather than a regex:

    >> [path,name,ext] = fileparts('/A/B/C/D/foo/bar')
    path = /A/B/C/D/foo
    name = bar
    ext =
    

    If bar has an extension, then it would be:

    >> [path,name,ext] = fileparts('/A/B/C/D/foo/bar.txt')
    path = /A/B/C/D/foo
    name = bar
    ext = .txt
    >> nameext = [name ext]
    nameext = bar.txt