function metadata = findExample(arg)

% Copyright 2017-2021 The MathWorks, Inc.

% By component/main or component-main.
match = regexp(arg,'^(\w+)[/-](\w+)$','tokens','once');
if ~isempty(match)
    component = match{1};
    source = match{2};

    componentExamplesDir = matlab.internal.examples.componentExamplesDir(component);
    examplesXml = fullfile(componentExamplesDir,'examples.xml');

    expression = "/demos/demoitem[source/text()='" + source + "']/metadata/text()";
    nodeList = evaluate(matlab.io.xml.xpath.Evaluator, expression, examplesXml, matlab.io.xml.xpath.EvalResultType.NodeSet);
    if length(nodeList) == 1
        metadata = nodeList(1).getTextContent;
        id = [component '-' metadata];
        metadata = matlab.internal.examples.readMetadata(id, componentExamplesDir);
        return;
    end
    error(em('ExampleNotFound',source,examplesXml))
end

error(em('InvalidArgument',arg))

function m = em(id,varargin)
m = message(['MATLAB:examples:' id],varargin{:});
