regexp: match the entire expression

1 回表示 (過去 30 日間)
mary
mary 2022 年 11 月 11 日
コメント済み: mary 2022 年 11 月 12 日
Hi,
Is there any way to do the match between an expression and a pattern perfectly and not partially?
Example:
setStrings{1} = '2*x + 3';
setStrings{2} = '2*x';
first_kind = regexp(setStrings, '(?<A>-?\d+)\s*\*\s*x', 'names')
first_kind = 1×2 cell array
{1×1 struct} {1×1 struct}
second_kind = regexp(setStrings, '(?<A>-?\d+)\s*\*\s*x\s*(?<B>[+-]\s*\d+)', 'names')
second_kind = 1×2 cell array
{1×1 struct} {0×0 struct}
here both strings 1 and 2 are considered to be of first kind. What I want is to exclude that the expression 2 can be counted as the first kind because it does not have B. So probably the option 'names' should be changed into something that guarantees the perfect match, otherwise it excludes it. Here in this example we have a partial match.

採用された回答

Walter Roberson
Walter Roberson 2022 年 11 月 11 日
setStrings{1} = '2*x + 3';
setStrings{2} = '2*x';
first_kind = regexp(setStrings, '^\s*(?<A>-?\d+)\s*\*\s*x\s*$', 'names')
first_kind = 1×2 cell array
{0×0 struct} {1×1 struct}
second_kind = regexp(setStrings, '(?<A>-?\d+)\s*\*\s*x\s*(?<B>[+-]\s*\d+)', 'names')
second_kind = 1×2 cell array
{1×1 struct} {0×0 struct}
By default, ^ matches "immediately after the beginning of input" and $ matches "immediately before end of input". However if you add the option 'lineanchors' then $ matches immediately after the beginning of each input line and $ matches immediately before the end of each input line (so $ does not match the newline itself.) If you use 'lineanchors' then it is common that you will also end up needing the option 'dotexceptnewline'
  1 件のコメント
mary
mary 2022 年 11 月 12 日
Thanks

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by