How to extract between a keyword the end statement in a code?

4 ビュー (過去 30 日間)
Jeremiah Beatima
Jeremiah Beatima 2021 年 9 月 23 日
編集済み: Salman Ahmed 2021 年 10 月 14 日
I create a program that reads and extract certain parts of a different side of code. The issue is the comment also contains my 'end' searchword and stops before I want it to.
filetoread = fileread(sample_code.m)
keyword = 'mybeginningsearchword'
pulledText = string(extractBetween(filetoread, keyword, 'end', 'boundaries', 'inclusive')
when I run it for most part of the code, it works, but some files have the word 'end' in the comment. resulting in
keyword
temp 79 %temp in F
rain 12 % chance of rain in percent
day M% current day
time 12:30 %this is where the search come to an end
this part is missing
weather cloudy %current weather
end %where I want it the search to end
I've tried to used a pattern using pat= newline +'end' , append(newline, 'end')
I tried to used ' end'. and it work for this file but it does not work on the previous files it work for.
I could turn it to string and search for the second or nth time end occurences but it won't for for other files that don't have a second end.
Is there anyway to search till the end of the block. I think '(?(cond)expr1|expr2)' in regexp would be the path I need to take but I don't have the skills or knowledge combined it.

回答 (1 件)

Salman Ahmed
Salman Ahmed 2021 年 10 月 14 日
編集済み: Salman Ahmed 2021 年 10 月 14 日
Hi Jeremiah,
I understand that you are trying to extract between a keyword and end statement and the presence of end in comments is stopping the extraction prematurely. A possible workaround could be to strip the file off the comments before extracting. I am attaching a link to MATLAB file exchange here which would help you eliminate the comments : MATLAB comment remover. Hope it resolves your issue.

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by