How to use variables in regular expressions?

11 views (last 30 days)
Ana Alonso
Ana Alonso on 21 Jun 2019
Answered: Aaron Greisen on 6 Sep 2022
Hello,
I have two directory names and I want to find the string that is in one name, but not the other.
DIR = '/mnt/disk2/SongLibrary/EntireSongDevelopment/Data/';
songdir = '/mnt/disk2/SongLibrary/EntireSongDevelopment/Data/day43samba/R372/38';
For example, I want to get the following output from the above two directories:
result = 'day43samba/R372/38';
The redundant parts are always at the beginning of the strings, so I've been trying to use lookaround assertions to find everything in songdir that comes after DIR. This is what I have so far:
regexp(songdir,'(?<=${DIR}).*','match');
Unfortunately, this doesn't return anything. Can you incorporate variables into regular expressions? If so, how?
I'm also not married to the idea of using regexp to solve the problem. I tried using setdiff, but that only returns the characters in songdir and not in DIR.
test = setdiff(songdir,DIR)
test =
'3478R'
Any advice is appreciated!

Answers (2)

infinity
infinity on 21 Jun 2019
Hello,
Here is a simple way that you can use
n = length(DIR);
result = songdir(n:end)

Aaron Greisen
Aaron Greisen on 6 Sep 2022
infinity has a simple solution that should work for you in this case without using regular expressions, but when trying to use variables in a regular expression you can try using strcat:
regexp(songdir, strcat('(?<=', DIR, ').*'), 'match');

Categories

Find more on File Operations in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!