Need Some help with regexp
11 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hello Everyone , I am trying to build a regular expression for the following code :
function myValue = getmyValue(object)
switch object
case 'fruit.Apple'
x={'str1','str2','str3','str4','str5','str6','str7','str8','str9','str10'};
case 'fruit.Banana'
x={'PH1','PH2','PH3','PH4','PH5','PH6','PH7','PH8','PH9','PH10'};
case 'fruit.mango'
x={'Val1','Val2','Val3','Val4','Val5','Val6','Val7','Val8','Val9','Val10'};
case 'bird.Eagle '
x={'Obj1','Obj2','Obj3','Obj4','Obj5','Obj6','Obj7','Obj8','Obj9','Obj10'};
case 'animal.lion'
x={'Sp1','Sp2','Sp3','Sp4','Sp5','Sp6','Sp7','Sp8','Sp9','Sp10'};
end
This is my Code upon which a regular expression with following conditions needs to be applied :
1) After reading this code in a String format , I need to replace the value of x (which are some strings) by %searching its corresponding object..
2) For example//// I need to search for 'fruit.mango' from this code and replace the corresponding x value {Val1 ,Val2 ,....} with my own string (Lets Say, x={'ASDF','zxc','qwe','sdfdf','asas'};)
Can anyone point out how to do that// I am new to these regular expressions.. I can find out the Object(fruit.Apple) %But I am finding it difficult to replace the string in the next line.
0 Commenti
Risposte (1)
Walter Roberson
il 19 Apr 2016
filecontent = fileread('getmyValue.m');
newstrings = '''ASDF'',''zxc'',''qwe'',''sdfdf'',''asas'''; %no {}
newcontent = regexprep(filecontent, '(?<=''fruit\.mango''\s+x={)([^}]*)(?=})', newstrings);
Now newcontent is a string that can be further processed or fwrite() to a file.
2 Commenti
Walter Roberson
il 21 Apr 2016
You can use string processing to build the pattern and the replacement.
For example,
target = 'fruit.mango';
x = {'ASDF','zxc','qwe','sdfdf','asas'};
escaped_target = regexprep(target, '\.', '\\.');
searchpat = sprintf('(?<=''%s''\\s+x={)([^}]*)(?=})', escaped_target);
newstrings = ['{''', strjoin( x, ''','''), '''};' ];
newcontent = regexprep(currentcontent, searchpat, newstrings);
Vedere anche
Categorie
Scopri di più su Characters and Strings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!