Using regexp to match multiple substrings, two questions

조회 수: 3 (최근 30일)
Aram Schiffman
Aram Schiffman 2017년 11월 27일
댓글: Aram Schiffman 2017년 11월 27일
Hi all, Simple two part question.
1) I have a function where regexp needs to match two terms in a string.
st1='This string is going to be searched'
Expression should evaluate to True if st1 contains 'going' and 'search'.
I stole the following syntax from an old StackOverflow thread. I understand why it works. My question is, why is the '^' necessary? What is it doing?
hasMatch=~isempty(regexp(st1,'^(?=.*going).*(?=.*search).*'))
2) This code will be in a function. I would like to generalize it to any number of substrings that need to be matched. I understand varargin, but I'm not clever enough with regexp to code an arbitrary number of substrings that must be matched. Any help would be welcome.
Thanks!
-Aram
  댓글 수: 3
Aram Schiffman
Aram Schiffman 2017년 11월 27일
편집: Aram Schiffman 2017년 11월 27일
Right, good point. Answer is order-independent. I just need all N substrings to be matched -- somewhere.
Thanks, Aram
Stephen23
Stephen23 2017년 11월 27일
@Aram Schiffman: a regular expression is fundamentally order-dependent. You should consider other solutions.

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

채택된 답변

Stephen23
Stephen23 2017년 11월 27일
편집: Stephen23 2017년 11월 27일
You do not need to use regexp to fulfill the given requirements:
>> st1 = 'This string is going to be searched';
>> fun = @(s)~isempty(strfind(st1,s));
>> all(cellfun(fun,{'going','search'}))
ans = 1
>> all(cellfun(fun,{'going','elephant'}))
ans = 0
You can put this into a function, and provide as many inputs as you want:
function out = areinstr(str,varargin)
fun = @(s)~isempty(strfind(str,s));
out = all(cellfun(fun,varargin));
end
and tested:
>> areinstr(st1,'going','search','This')
ans = 1
>> areinstr(st1,'going','search','This','string')
ans = 1
>> areinstr(st1,'going','search','This','string','antelope')
ans = 0
  댓글 수: 3
Stephen23
Stephen23 2017년 11월 27일
"I thought there was a way for them not to beI thought there was a way for them not to be"
There are some hacks that can be used to make them order-independent, but they make expression much more complex and slow.
Remember to accept the answer that best helps you to resolve your original question. That is the easiest way to show your thanks to the volunteers who helped you.
Aram Schiffman
Aram Schiffman 2017년 11월 27일
Done. Thank you.

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

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by