-
Notifications
You must be signed in to change notification settings - Fork 1
/
findStrPos.m
54 lines (50 loc) · 1.46 KB
/
findStrPos.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
function indices = findStrPos( str , pattern , opts )
% str the space that is seached (char array, cell array, string array)
% pattern the search keyword or pattern
% opts options: 0 - normal search ||| 'regex' - regex search
% Philipp Schneider 2018
if nargin == 2
opts = 0;
end
% convert str type to cell
switch class(str)
case 'string'
str = cellstr(strtrim(str));
case 'char'
str = cellstr(str);
case 'cell'
otherwise
error('input 1 of findStrPos doesn''t correct type');
end
% convert pattern type to cell
switch class(pattern)
case 'string'
pattern = char(pattern);
case 'char'
pattern = cellstr(pattern);
case 'cell'
otherwise
error('input 2 of findStrPos doesn''t correct type');
end
[rows,cols] = size(pattern);
switch opts
case 0
for i = 1:(rows*cols)
ind = find(strcmp(str, pattern(i)));
indices(1:length(ind),i) = ind;
end
case 'regex'
if opts
for i = 1:(rows*cols)
match = regexp(str, pattern(i), 'match');
ind = find(~cellfun(@isempty,match));
indices(1:length(ind),i) = ind;
end
end
otherwise
error('define correct option. 0 for basic search or ''regex''');
end
if any( size(pattern) == 0) || (any(size(indices)==0))
indices = [];
end
end