Is there a less bug-prone way to include quote in selector string variable when defining opt.TableSelector?

My situation is to readtable( ) several tables, each of which has a specific title, from an html file. I have come up with a couple solutions to define TableSelector, but it is bug prone. Is there a better way?
opt = htmlImportOptions;
opt.TableSelector = "//TABLE[contains(.,'Cash dividends')]";
headings = ["'Music'", "Photo"];
%% correct selector string, but bug prone
opt.TableSelector = "//TABLE[contains(.," + headings(1) +")]";
opt.TableSelector
ans = "//TABLE[contains(.,'Music')]"
% readtable(html, opt)
%% wrong solution
opt.TableSelector = "TABLE[contains(.,"+ headings(2) +")]";
opt.TableSelector
ans = "TABLE[contains(.,Photo)]"
% readtable(html, opt) % would return no error message, so it's a bug source.
%% fix the wrong solution
str1 = "TABLE[contains(.,'";
str2 = "')]";
opt.TableSelector = str1 + headings(2) + str2;
opt.TableSelector
ans = "TABLE[contains(.,'Photo')]"
% readtable(html, opt)

댓글 수: 3

Is it possible that the headings to use could ever contain ' themselves? If so then it will be necessary to protect against that.
Reading further, I see that we do not need to worry about "escape characters" -- for example if the user specified 'Music\' then the \' would be treated as two distinct unrelated characters, not as indicating "the next character is a literal quote". So we do not need to "sanitize" the input against an assortment of characters.
We do, however, potentially need to worry about the possibility that the headings contain ' characters or " characters.
@Walter Roberson Thanks for the comment. No, the headings would not have ' or " themselves.

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

 채택된 답변

opt.TableSelector = "TABLE[contains(.,'" + headings(2) + "')]";
or
opt.TableSelector = compose("Table[contains(.,'%s')", headings(2));

추가 답변 (0개)

카테고리

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

제품

릴리스

R2023a

질문:

2023년 5월 15일

댓글:

2023년 5월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by