regexp: match the entire expression
조회 수: 2 (최근 30일)
이전 댓글 표시
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')
second_kind = regexp(setStrings, '(?<A>-?\d+)\s*\*\s*x\s*(?<B>[+-]\s*\d+)', 'names')
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.
댓글 수: 0
채택된 답변
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')
second_kind = regexp(setStrings, '(?<A>-?\d+)\s*\*\s*x\s*(?<B>[+-]\s*\d+)', 'names')
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'
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!