Abbreviate regexp: match a if present, else match b

조회 수: 2(최근 30일)
Jonas
Jonas 2022년 11월 9일
댓글: Jonas 2022년 11월 14일
dear community,
can someone abbreviate the follwing if else in a single regexp?
str1='this is } and this is }, and this is }';
str2='this is } and this is } and this is }';
if regexp(str1,'},','once')
where=regexp(str1,'},')
else
where=regexp(str1,'}')
end
where = 23
if regexp(str2,'},','once')
where=regexp(str2,'},')
else
where=regexp(str2,'}')
end
where = 1×3
9 23 38
i tried to adapt the example of the documentation, but was not able to make it work
(?(cond)expr1|expr2)
If condition cond is true, then match expr1. Otherwise, match expr2.
'Mr(s?)\..*?(?(1)her|his) \w*' matches text that includes her when the text begins with Mrs, or that includes his when the text begins with Mr.
regexp(str1,'}(,?)(?(1)},|})')
ans = []
best regards
Jonas

채택된 답변

Stephen23
Stephen23 2022년 11월 14일
편집: Stephen23 2022년 11월 14일
It is possible to combine them, but it will be fiddly and not very efficient because it requires in some way checking the entire text for the existence of the specified substring when performing every single match. Here is one approach that combines a conditional operator with a dynamic command:
st1 = 'this is } and this is }, and this is }';
st2 = 'this is } and this is } and this is }';
rgx = '\}(?(?@contains([$`,$&,$''],''},'')),)';
regexp(st1,rgx)
ans = 23
regexp(st2,rgx)
ans = 1×3
9 23 38
Broken down:
% '\}(?(?@contains([$`,$&,$''],''},'')),)';
% \} literal curly brace
% (?( ),) conditional match comma
% ?@contains( , ) dynamic check text content:
% [$`,$&,$''] entire input text
% ''},'' literal curly-brace & comma
You could probably do something similar with lookarounds. But as noted, the condition command will be called again and again with each match... this is rather inefficient, because your condition does not change. I do not see an obvious way to avoid this. A more efficient approach (if you are able to relax your requirements) is probably to check that condition once before calling regexp:
rgx = '\}(?(?@tmp),)';
tmp = contains(st1,'},');
regexp(st1,rgx)
ans = 23
tmp = contains(st2,'},');
regexp(st2,rgx)
ans = 1×3
9 23 38
  댓글 수: 1
Jonas
Jonas 2022년 11월 14일
it seems like i misunderstood the concept of condition in this case since the condition is checked in each case (like you said). thanks for your code!

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

추가 답변(0개)

범주

Find more on Characters and Strings in Help Center and File Exchange

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by