How to use variables in regular expressions?
2 views (last 30 days)
Show older comments
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!
0 Comments
Answers (2)
infinity
on 21 Jun 2019
Hello,
Here is a simple way that you can use
n = length(DIR);
result = songdir(n:end)
0 Comments
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');
0 Comments
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!