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.

답변 (1개)

Walter Roberson
Walter Roberson 2016년 4월 19일

0 개 추천

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

Aryan Sinha
Aryan Sinha 2016년 4월 21일
Hello walter ,
Thanks .. is there any way around by which I can automate this instead of giving manual inputs..
Example : Since it is a big switch case, i want to update all different values in a for loop
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);

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

질문:

2016년 4월 19일

댓글:

2016년 4월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by