5582
|
1 /* |
|
2 |
7017
|
3 Copyright (C) 2005, 2006, 2007 David Bateman |
7016
|
4 Copyright (C) 2002, 2003, 2004, 2005 Paul Kienzle |
|
5 |
|
6 This file is part of Octave. |
5582
|
7 |
|
8 Octave is free software; you can redistribute it and/or modify it |
|
9 under the terms of the GNU General Public License as published by the |
7016
|
10 Free Software Foundation; either version 3 of the License, or (at your |
|
11 option) any later version. |
5582
|
12 |
|
13 Octave is distributed in the hope that it will be useful, but WITHOUT |
|
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
16 for more details. |
|
17 |
|
18 You should have received a copy of the GNU General Public License |
7016
|
19 along with Octave; see the file COPYING. If not, see |
|
20 <http://www.gnu.org/licenses/>. |
5582
|
21 |
|
22 */ |
|
23 |
|
24 #ifdef HAVE_CONFIG_H |
|
25 #include <config.h> |
|
26 #endif |
|
27 |
5773
|
28 #include <algorithm> |
5765
|
29 #include <sstream> |
|
30 |
5582
|
31 #include "defun-dld.h" |
|
32 #include "error.h" |
|
33 #include "gripes.h" |
|
34 #include "oct-obj.h" |
|
35 #include "utils.h" |
|
36 |
|
37 #include "Cell.h" |
|
38 #include "oct-map.h" |
|
39 #include "str-vec.h" |
5785
|
40 #include "quit.h" |
|
41 #include "parse.h" |
5582
|
42 |
|
43 #ifdef HAVE_PCRE |
|
44 #include <pcre.h> |
|
45 #else |
|
46 #ifdef HAVE_REGEX |
|
47 #ifdef __MINGW32__ |
|
48 #define __restrict |
|
49 #endif |
|
50 #include <regex.h> |
|
51 #endif |
|
52 #endif |
|
53 |
5785
|
54 // The regexp is constructed as a linked list to avoid resizing the |
|
55 // return values in arrays at each new match. |
|
56 |
|
57 // FIXME don't bother collecting and composing return values the user |
|
58 // doesn't want. |
|
59 |
|
60 class regexp_elem |
5582
|
61 { |
5785
|
62 public: |
5787
|
63 regexp_elem (const string_vector& _named_token, const Cell& _t, |
|
64 const std::string& _m, const Matrix& _te, double _s, |
|
65 double _e) : |
5785
|
66 named_token (_named_token), t (_t), m (_m), te (_te), s (_s), e (_e) { } |
|
67 |
|
68 regexp_elem (const regexp_elem &a) : named_token (a.named_token), t (a.t), |
|
69 m (a.m), te (a.te), s (a.s), e (a.e) |
|
70 { } |
|
71 |
|
72 string_vector named_token; |
|
73 Cell t; |
|
74 std::string m; |
|
75 Matrix te; |
|
76 double s; |
|
77 double e; |
|
78 }; |
|
79 |
|
80 typedef std::list<regexp_elem>::const_iterator const_iterator; |
|
81 |
|
82 static int |
|
83 octregexp_list (const octave_value_list &args, const std::string &nm, |
|
84 bool case_insensitive, std::list<regexp_elem> &lst, |
|
85 string_vector &named, int &nopts) |
|
86 { |
|
87 int sz = 0; |
5582
|
88 #if defined (HAVE_REGEX) || defined (HAVE_PCRE) |
|
89 int nargin = args.length(); |
|
90 bool once = false; |
5779
|
91 bool lineanchors = false; |
|
92 bool dotexceptnewline = false; |
|
93 bool freespacing = false; |
5582
|
94 |
5785
|
95 nopts = nargin - 2; |
|
96 |
5582
|
97 std::string buffer = args(0).string_value (); |
|
98 if (error_state) |
|
99 { |
|
100 gripe_wrong_type_arg (nm.c_str(), args(0)); |
5785
|
101 return 0; |
5582
|
102 } |
|
103 |
|
104 std::string pattern = args(1).string_value (); |
|
105 if (error_state) |
|
106 { |
|
107 gripe_wrong_type_arg (nm.c_str(), args(1)); |
5785
|
108 return 0; |
5582
|
109 } |
|
110 |
|
111 for (int i = 2; i < nargin; i++) |
|
112 { |
|
113 std::string str = args(i).string_value(); |
|
114 if (error_state) |
|
115 { |
|
116 error ("%s: optional arguments must be strings", nm.c_str()); |
|
117 break; |
|
118 } |
|
119 std::transform (str.begin (), str.end (), str.begin (), tolower); |
|
120 if (str.find("once", 0) == 0) |
|
121 { |
|
122 once = true; |
|
123 nopts--; |
|
124 } |
5779
|
125 else if (str.find("matchcase", 0) == 0) |
|
126 { |
|
127 case_insensitive = false; |
|
128 nopts--; |
|
129 } |
|
130 else if (str.find("ignorecase", 0) == 0) |
|
131 { |
|
132 case_insensitive = true; |
|
133 nopts--; |
|
134 } |
5785
|
135 else if (str.find("dotall", 0) == 0) |
5779
|
136 { |
5785
|
137 dotexceptnewline = false; |
|
138 nopts--; |
|
139 } |
|
140 else if (str.find("stringanchors", 0) == 0) |
|
141 { |
|
142 lineanchors = false; |
5779
|
143 nopts--; |
|
144 } |
|
145 else if (str.find("literalspacing", 0) == 0) |
|
146 { |
|
147 freespacing = false; |
|
148 nopts--; |
|
149 } |
5785
|
150 #if HAVE_PCRE |
|
151 // Only accept these options with pcre |
|
152 else if (str.find("dotexceptnewline", 0) == 0) |
|
153 { |
|
154 dotexceptnewline = true; |
|
155 nopts--; |
|
156 } |
|
157 else if (str.find("lineanchors", 0) == 0) |
|
158 { |
|
159 lineanchors = true; |
|
160 nopts--; |
|
161 } |
|
162 else if (str.find("freespacing", 0) == 0) |
|
163 { |
|
164 freespacing = true; |
|
165 nopts--; |
|
166 } |
5582
|
167 else if (str.find("start", 0) && str.find("end", 0) && |
|
168 str.find("tokenextents", 0) && str.find("match", 0) && |
|
169 str.find("tokens", 0) && str.find("names", 0)) |
|
170 error ("%s: unrecognized option", nm.c_str()); |
|
171 #else |
5779
|
172 else if (str.find("names", 0) == 0 || |
|
173 str.find("dotexceptnewline", 0) == 0 || |
|
174 str.find("lineanchors", 0) == 0 || |
|
175 str.find("freespacing", 0) == 0) |
5785
|
176 error ("%s: %s not implemented in this version", str.c_str(), nm.c_str()); |
5582
|
177 else if (str.find("start", 0) && str.find("end", 0) && |
|
178 str.find("tokenextents", 0) && str.find("match", 0) && |
|
179 str.find("tokens", 0)) |
|
180 error ("%s: unrecognized option", nm.c_str()); |
|
181 #endif |
|
182 } |
|
183 |
|
184 if (!error_state) |
|
185 { |
5785
|
186 Cell t; |
|
187 std::string m; |
|
188 double s, e; |
5582
|
189 |
|
190 // named tokens "(?<name>...)" are only treated with PCRE not regex. |
|
191 #if HAVE_PCRE |
|
192 // The syntax of named tokens in pcre is "(?P<name>...)" while we need |
|
193 // a syntax "(?<name>...)", so fix that here. Also an expression like |
|
194 // "(?<first>\w+)\s+(?<last>\w+)|(?<last>\w+),\s+(?<first>\w+)" should |
|
195 // be perfectly legal, while pcre does not allow the same named token |
5619
|
196 // name on both sides of the alternative. Also fix that here by replacing |
|
197 // name tokens by dummy names, and dealing with the dummy names later. |
5582
|
198 |
5619
|
199 size_t pos = 0; |
|
200 size_t new_pos; |
|
201 int nnames = 0; |
|
202 int inames = 0; |
5765
|
203 std::ostringstream buf; |
5619
|
204 Array<int> named_idx; |
5582
|
205 |
5619
|
206 while ((new_pos = pattern.find ("(?<",pos)) != NPOS) |
|
207 { |
|
208 size_t tmp_pos = pattern.find_first_of ('>',new_pos); |
5582
|
209 |
5619
|
210 if (tmp_pos == NPOS) |
|
211 { |
|
212 error ("syntax error in pattern"); |
|
213 break; |
|
214 } |
|
215 |
|
216 std::string tmp_name = pattern.substr(new_pos+3,tmp_pos-new_pos-3); |
|
217 bool found = false; |
|
218 |
|
219 for (int i = 0; i < nnames; i++) |
|
220 if (named(i) == tmp_name) |
|
221 { |
|
222 named_idx.resize(inames+1); |
|
223 named_idx(inames) = i; |
|
224 found = true; |
|
225 break; |
|
226 } |
|
227 if (! found) |
|
228 { |
|
229 named_idx.resize(inames+1); |
|
230 named_idx(inames) = nnames; |
|
231 named.append(tmp_name); |
|
232 nnames++; |
|
233 } |
|
234 |
|
235 if (new_pos - pos > 0) |
|
236 buf << pattern.substr(pos,new_pos-pos); |
|
237 if (inames < 10) |
|
238 buf << "(?P<n00" << inames++; |
|
239 else if (inames < 100) |
|
240 buf << "(?P<n0" << inames++; |
|
241 else |
|
242 buf << "(?P<n" << inames++; |
|
243 pos = tmp_pos; |
|
244 } |
|
245 |
5765
|
246 buf << pattern.substr(pos); |
5619
|
247 |
|
248 if (error_state) |
5785
|
249 return 0; |
5582
|
250 |
|
251 // Compile expression |
|
252 pcre *re; |
|
253 const char *err; |
|
254 int erroffset; |
5765
|
255 std::string buf_str = buf.str (); |
|
256 re = pcre_compile (buf_str.c_str (), |
5779
|
257 (case_insensitive ? PCRE_CASELESS : 0) | |
|
258 (dotexceptnewline ? 0 : PCRE_DOTALL) | |
|
259 (lineanchors ? PCRE_MULTILINE : 0) | |
|
260 (freespacing ? PCRE_EXTENDED : 0), |
5765
|
261 &err, &erroffset, NULL); |
5582
|
262 |
|
263 if (re == NULL) { |
|
264 error("%s: %s at position %d of expression", nm.c_str(), |
|
265 err, erroffset); |
5785
|
266 return 0; |
5582
|
267 } |
|
268 |
|
269 int subpatterns; |
|
270 int namecount; |
|
271 int nameentrysize; |
|
272 char *nametable; |
|
273 int idx = 0; |
|
274 |
|
275 pcre_fullinfo(re, NULL, PCRE_INFO_CAPTURECOUNT, &subpatterns); |
|
276 pcre_fullinfo(re, NULL, PCRE_INFO_NAMECOUNT, &namecount); |
|
277 pcre_fullinfo(re, NULL, PCRE_INFO_NAMEENTRYSIZE, &nameentrysize); |
|
278 pcre_fullinfo(re, NULL, PCRE_INFO_NAMETABLE, &nametable); |
|
279 |
|
280 OCTAVE_LOCAL_BUFFER(int, ovector, (subpatterns+1)*3); |
|
281 OCTAVE_LOCAL_BUFFER(int, nidx, namecount); |
|
282 |
|
283 for (int i = 0; i < namecount; i++) |
|
284 { |
|
285 // Index of subpattern in first two bytes MSB first of name. |
5619
|
286 // Extract index. |
5779
|
287 nidx[i] = (static_cast<int>(nametable[i*nameentrysize])) << 8 | |
|
288 static_cast<int>(nametable[i*nameentrysize+1]); |
5582
|
289 } |
|
290 |
|
291 while(true) |
|
292 { |
5785
|
293 OCTAVE_QUIT; |
|
294 |
5582
|
295 int matches = pcre_exec(re, NULL, buffer.c_str(), |
|
296 buffer.length(), idx, |
|
297 (idx ? PCRE_NOTBOL : 0), |
|
298 ovector, (subpatterns+1)*3); |
|
299 |
|
300 if (matches < 0 && matches != PCRE_ERROR_NOMATCH) |
|
301 { |
|
302 error ("%s: internal error calling pcre_exec", nm.c_str()); |
|
303 pcre_free(re); |
5785
|
304 return 0; |
5582
|
305 } |
|
306 else if (matches == PCRE_ERROR_NOMATCH) |
|
307 break; |
5779
|
308 else if (ovector[1] <= ovector[0]) |
|
309 break; |
5582
|
310 else |
|
311 { |
5619
|
312 int pos_match = 0; |
5785
|
313 Matrix te(matches-1,2); |
5582
|
314 for (int i = 1; i < matches; i++) |
|
315 { |
5619
|
316 if (ovector[2*i] >= 0 && ovector[2*i+1] > 0) |
|
317 { |
5785
|
318 te(pos_match,0) = double (ovector[2*i]+1); |
|
319 te(pos_match++,1) = double (ovector[2*i+1]); |
5619
|
320 } |
5582
|
321 } |
5785
|
322 te.resize(pos_match,2); |
|
323 s = double (ovector[0]+1); |
|
324 e = double (ovector[1]); |
5582
|
325 |
|
326 const char **listptr; |
|
327 int status = pcre_get_substring_list(buffer.c_str(), ovector, |
|
328 matches, &listptr); |
|
329 |
|
330 if (status == PCRE_ERROR_NOMEMORY) { |
|
331 error("%s: cannot allocate memory in pcre_get_substring_list", |
|
332 nm.c_str()); |
|
333 pcre_free(re); |
5785
|
334 return 0; |
5582
|
335 } |
|
336 |
5619
|
337 Cell cell_t (dim_vector(1,pos_match)); |
|
338 pos_match = 0; |
5582
|
339 for (int i = 1; i < matches; i++) |
5619
|
340 if (ovector[2*i] >= 0 && ovector[2*i+1] > 0) |
|
341 cell_t(pos_match++) = std::string(*(listptr+i)); |
5582
|
342 |
5785
|
343 m = std::string(*listptr); |
|
344 t = cell_t; |
|
345 |
|
346 string_vector named_tokens(nnames); |
5619
|
347 if (namecount > 0) |
|
348 for (int i = 1; i < matches; i++) |
|
349 { |
|
350 if (ovector[2*i] >= 0 && ovector[2*i+1] > 0) |
|
351 { |
5785
|
352 named_tokens(named_idx(i-1)) = |
|
353 std::string(*(listptr+nidx[i-1])); |
5619
|
354 } |
|
355 } |
5582
|
356 |
|
357 pcre_free_substring_list(listptr); |
|
358 |
5785
|
359 regexp_elem new_elem (named_tokens, t, m, te, s, e); |
|
360 lst.push_back (new_elem); |
|
361 idx = ovector[1]; |
|
362 sz++; |
|
363 |
5582
|
364 if (once) |
|
365 break; |
|
366 |
|
367 } |
|
368 } |
|
369 |
|
370 pcre_free(re); |
|
371 #else |
|
372 regex_t compiled; |
|
373 int err=regcomp(&compiled, pattern.c_str(), REG_EXTENDED | |
|
374 (case_insensitive ? REG_ICASE : 0)); |
|
375 if (err) |
|
376 { |
|
377 int len = regerror(err, &compiled, NULL, 0); |
5760
|
378 OCTAVE_LOCAL_BUFFER (char, errmsg, len); |
|
379 regerror(err, &compiled, errmsg, len); |
|
380 error("%s: %s in pattern (%s)", nm.c_str(), errmsg, |
|
381 pattern.c_str()); |
5582
|
382 regfree(&compiled); |
5785
|
383 return 0; |
5582
|
384 } |
|
385 |
|
386 int subexpr = 1; |
|
387 int idx = 0; |
|
388 for (unsigned int i=0; i < pattern.length(); i++) |
|
389 subexpr += ( pattern[i] == '(' ? 1 : 0 ); |
|
390 OCTAVE_LOCAL_BUFFER (regmatch_t, match, subexpr ); |
|
391 |
|
392 while(true) |
|
393 { |
5785
|
394 OCTAVE_QUIT; |
|
395 |
5582
|
396 if (regexec(&compiled, buffer.c_str() + idx, subexpr, |
|
397 match, (idx ? REG_NOTBOL : 0)) == 0) |
|
398 { |
|
399 // Count actual matches |
|
400 int matches = 0; |
|
401 while (matches < subexpr && match[matches].rm_so >= 0) |
|
402 matches++; |
|
403 |
5785
|
404 s = double (match[0].rm_so+1+idx); |
|
405 e = double (match[0].rm_eo+idx); |
|
406 Matrix te(matches-1,2); |
5582
|
407 for (int i = 1; i < matches; i++) |
|
408 { |
5785
|
409 te(i-1,0) = double (match[i].rm_so+1+idx); |
|
410 te(i-1,1) = double (match[i].rm_eo+idx); |
5582
|
411 } |
|
412 |
5785
|
413 m = buffer.substr (match[0].rm_so+idx, |
5582
|
414 match[0].rm_eo-match[0].rm_so); |
|
415 |
|
416 Cell cell_t (dim_vector(1,matches-1)); |
|
417 for (int i = 1; i < matches; i++) |
|
418 cell_t(i-1) = buffer.substr (match[i].rm_so+idx, |
|
419 match[i].rm_eo-match[i].rm_so); |
5785
|
420 t = cell_t; |
5582
|
421 |
|
422 idx += match[0].rm_eo; |
5785
|
423 |
5866
|
424 string_vector sv; |
|
425 regexp_elem new_elem (sv, t, m, te, s, e); |
5785
|
426 lst.push_back (new_elem); |
5582
|
427 sz++; |
|
428 |
|
429 if (once) |
|
430 break; |
|
431 } |
|
432 else |
|
433 break; |
|
434 } |
|
435 regfree(&compiled); |
|
436 #endif |
5785
|
437 } |
|
438 #else |
|
439 error ("%s: not available in this version of Octave", nm.c_str()); |
|
440 #endif |
|
441 return sz; |
|
442 } |
5582
|
443 |
5785
|
444 static octave_value_list |
|
445 octregexp (const octave_value_list &args, int nargout, const std::string &nm, |
|
446 bool case_insensitive) |
|
447 { |
|
448 octave_value_list retval; |
|
449 int nargin = args.length(); |
|
450 std::list<regexp_elem> lst; |
|
451 string_vector named; |
|
452 int nopts; |
|
453 int sz = octregexp_list (args, nm, case_insensitive, lst, named, nopts); |
|
454 |
|
455 if (! error_state) |
|
456 { |
|
457 // Converted the linked list in the correct form for the return values |
|
458 |
|
459 octave_idx_type i = 0; |
|
460 #ifdef HAVE_PCRE |
|
461 Octave_map nmap; |
|
462 if (sz == 1) |
|
463 { |
|
464 for (int j = 0; j < named.length(); j++) |
|
465 nmap.assign (named(j), lst.begin()->named_token(j)); |
|
466 retval(5) = nmap; |
|
467 } |
|
468 else |
|
469 { |
|
470 for (int j = 0; j < named.length (); j++) |
|
471 { |
|
472 i = 0; |
|
473 Cell tmp(dim_vector (1, sz)); |
|
474 for (const_iterator p = lst.begin(); p != lst.end(); p++) |
|
475 tmp(i++) = p->named_token(j); |
|
476 nmap.assign (named(j), octave_value (tmp)); |
|
477 } |
|
478 retval(5) = nmap; |
|
479 } |
|
480 #else |
|
481 retval(5) = Octave_map(); |
|
482 #endif |
|
483 |
|
484 Cell t (dim_vector(1, sz)); |
|
485 i = 0; |
|
486 for (const_iterator p = lst.begin(); p != lst.end(); p++) |
|
487 t(i++) = p->t; |
5582
|
488 retval(4) = t; |
5785
|
489 |
|
490 Cell m (dim_vector(1, sz)); |
|
491 i = 0; |
|
492 for (const_iterator p = lst.begin(); p != lst.end(); p++) |
|
493 m(i++) = p->m; |
5582
|
494 retval(3) = m; |
5785
|
495 |
|
496 |
|
497 Cell te (dim_vector(1, sz)); |
|
498 i = 0; |
|
499 for (const_iterator p = lst.begin(); p != lst.end(); p++) |
|
500 te(i++) = p->te; |
5582
|
501 retval(2) = te; |
5785
|
502 |
|
503 NDArray e (dim_vector(1, sz)); |
|
504 i = 0; |
|
505 for (const_iterator p = lst.begin(); p != lst.end(); p++) |
|
506 e(i++) = p->e; |
5582
|
507 retval(1) = e; |
5785
|
508 |
|
509 NDArray s (dim_vector(1, sz)); |
|
510 i = 0; |
|
511 for (const_iterator p = lst.begin(); p != lst.end(); p++) |
|
512 s(i++) = p->s; |
5582
|
513 retval(0) = s; |
|
514 |
|
515 // Alter the order of the output arguments |
|
516 if (nopts > 0) |
|
517 { |
|
518 int n = 0; |
|
519 octave_value_list new_retval; |
|
520 new_retval.resize(nargout); |
|
521 |
|
522 OCTAVE_LOCAL_BUFFER (int, arg_used, 6); |
5785
|
523 for (int j = 0; j < 6; j++) |
|
524 arg_used[j] = false; |
5582
|
525 |
5785
|
526 for (int j = 2; j < nargin; j++) |
5582
|
527 { |
|
528 int k = 0; |
5785
|
529 std::string str = args(j).string_value(); |
5582
|
530 std::transform (str.begin (), str.end (), str.begin (), tolower); |
5779
|
531 if (str.find("once", 0) == 0 |
|
532 || str.find("stringanchors", 0) == 0 |
|
533 || str.find("lineanchors", 0) == 0 |
|
534 || str.find("matchcase", 0) == 0 |
|
535 || str.find("ignorecase", 0) == 0 |
|
536 || str.find("dotall", 0) == 0 |
|
537 || str.find("dotexceptnewline", 0) == 0 |
|
538 || str.find("literalspacing", 0) == 0 |
|
539 || str.find("freespacing", 0) == 0 |
|
540 ) |
5582
|
541 continue; |
|
542 else if (str.find("start", 0) == 0) |
|
543 k = 0; |
|
544 else if (str.find("end", 0) == 0) |
|
545 k = 1; |
|
546 else if (str.find("tokenextents", 0) == 0) |
|
547 k = 2; |
|
548 else if (str.find("match", 0) == 0) |
|
549 k = 3; |
|
550 else if (str.find("tokens", 0) == 0) |
|
551 k = 4; |
|
552 else if (str.find("names", 0) == 0) |
|
553 k = 5; |
|
554 |
|
555 new_retval(n++) = retval(k); |
|
556 arg_used[k] = true; |
|
557 |
|
558 if (n == nargout) |
|
559 break; |
|
560 } |
|
561 |
|
562 // Fill in the rest of the arguments |
|
563 if (n < nargout) |
|
564 { |
5785
|
565 for (int j = 0; j < 6; j++) |
5582
|
566 { |
5785
|
567 if (! arg_used[j]) |
|
568 new_retval(n++) = retval(j); |
5582
|
569 } |
|
570 } |
|
571 |
|
572 retval = new_retval; |
|
573 } |
|
574 } |
|
575 |
|
576 return retval; |
|
577 } |
|
578 |
6361
|
579 static octave_value_list |
|
580 octcellregexp (const octave_value_list &args, int nargout, const std::string &nm, |
|
581 bool case_insensitive) |
|
582 { |
|
583 octave_value_list retval; |
|
584 |
|
585 if (args(0).is_cell()) |
|
586 { |
|
587 OCTAVE_LOCAL_BUFFER (Cell, newretval, nargout); |
|
588 octave_value_list new_args = args; |
|
589 Cell cellstr = args(0).cell_value(); |
|
590 if (args(1).is_cell()) |
|
591 { |
|
592 Cell cellpat = args(1).cell_value(); |
|
593 |
|
594 if (cellpat.numel() == 1) |
|
595 { |
|
596 for (int j = 0; j < nargout; j++) |
|
597 newretval[j].resize(cellstr.dims()); |
|
598 |
|
599 new_args(1) = cellpat(0); |
|
600 |
|
601 for (octave_idx_type i = 0; i < cellstr.numel (); i++) |
|
602 { |
|
603 new_args(0) = cellstr(i); |
|
604 octave_value_list tmp = octregexp (new_args, nargout, nm, |
|
605 case_insensitive); |
|
606 |
|
607 if (error_state) |
|
608 break; |
|
609 |
|
610 for (int j = 0; j < nargout; j++) |
|
611 newretval[j](i) = tmp(j); |
|
612 } |
|
613 } |
|
614 else if (cellstr.numel() == 1) |
|
615 { |
|
616 for (int j = 0; j < nargout; j++) |
|
617 newretval[j].resize(cellpat.dims()); |
|
618 |
|
619 new_args(0) = cellstr(0); |
|
620 |
|
621 for (octave_idx_type i = 0; i < cellpat.numel (); i++) |
|
622 { |
|
623 new_args(1) = cellpat(i); |
|
624 octave_value_list tmp = octregexp (new_args, nargout, nm, |
|
625 case_insensitive); |
|
626 |
|
627 if (error_state) |
|
628 break; |
|
629 |
|
630 for (int j = 0; j < nargout; j++) |
|
631 newretval[j](i) = tmp(j); |
|
632 } |
|
633 } |
|
634 else if (cellstr.numel() == cellpat.numel()) |
|
635 { |
|
636 |
|
637 if (cellstr.dims() != cellpat.dims()) |
|
638 error ("%s: Inconsistent cell array dimensions", nm.c_str()); |
|
639 else |
|
640 { |
|
641 for (int j = 0; j < nargout; j++) |
|
642 newretval[j].resize(cellstr.dims()); |
|
643 |
|
644 for (octave_idx_type i = 0; i < cellstr.numel (); i++) |
|
645 { |
|
646 new_args(0) = cellstr(i); |
|
647 new_args(1) = cellpat(i); |
|
648 |
|
649 octave_value_list tmp = octregexp (new_args, nargout, nm, |
|
650 case_insensitive); |
|
651 |
|
652 if (error_state) |
|
653 break; |
|
654 |
|
655 for (int j = 0; j < nargout; j++) |
|
656 newretval[j](i) = tmp(j); |
|
657 } |
|
658 } |
|
659 } |
|
660 else |
|
661 error ("regexp: cell array arguments must be scalar or equal size"); |
|
662 } |
|
663 else |
|
664 { |
|
665 for (int j = 0; j < nargout; j++) |
|
666 newretval[j].resize(cellstr.dims()); |
|
667 |
|
668 for (octave_idx_type i = 0; i < cellstr.numel (); i++) |
|
669 { |
|
670 new_args(0) = cellstr(i); |
|
671 octave_value_list tmp = octregexp (new_args, nargout, nm, case_insensitive); |
|
672 |
|
673 if (error_state) |
|
674 break; |
|
675 |
|
676 for (int j = 0; j < nargout; j++) |
|
677 newretval[j](i) = tmp(j); |
|
678 } |
|
679 } |
|
680 |
|
681 if (!error_state) |
|
682 for (int j = 0; j < nargout; j++) |
|
683 retval(j) = octave_value (newretval[j]); |
|
684 } |
|
685 else if (args(1).is_cell()) |
|
686 { |
|
687 OCTAVE_LOCAL_BUFFER (Cell, newretval, nargout); |
|
688 octave_value_list new_args = args; |
|
689 Cell cellpat = args(1).cell_value(); |
|
690 |
|
691 for (int j = 0; j < nargout; j++) |
|
692 newretval[j].resize(cellpat.dims()); |
|
693 |
|
694 for (octave_idx_type i = 0; i < cellpat.numel (); i++) |
|
695 { |
|
696 new_args(1) = cellpat(i); |
|
697 octave_value_list tmp = octregexp (new_args, nargout, nm, case_insensitive); |
|
698 |
|
699 if (error_state) |
|
700 break; |
|
701 |
|
702 for (int j = 0; j < nargout; j++) |
|
703 newretval[j](i) = tmp(j); |
|
704 } |
|
705 |
|
706 if (!error_state) |
|
707 for (int j = 0; j < nargout; j++) |
|
708 retval(j) = octave_value (newretval[j]); |
|
709 } |
|
710 else |
|
711 retval = octregexp (args, nargout, nm, case_insensitive); |
|
712 |
|
713 return retval; |
|
714 |
|
715 } |
|
716 |
5582
|
717 DEFUN_DLD (regexp, args, nargout, |
|
718 "-*- texinfo -*-\n\ |
|
719 @deftypefn {Loadable Function} {[@var{s}, @var{e}, @var{te}, @var{m}, @var{t}, @var{nm}] =} regexp (@var{str}, @var{pat})\n\ |
|
720 @deftypefnx {Loadable Function} {[@dots{}] =} regexp (@var{str}, @var{pat}, @var{opts}, @dots{})\n\ |
|
721 \n\ |
|
722 Regular expression string matching. Matches @var{pat} in @var{str} and\n\ |
|
723 returns the position and matching substrings or empty values if there are\n\ |
|
724 none.\n\ |
|
725 \n\ |
|
726 The matched pattern @var{pat} can include any of the standard regex\n\ |
|
727 operators, including:\n\ |
|
728 \n\ |
|
729 @table @code\n\ |
|
730 @item .\n\ |
|
731 Match any character\n\ |
|
732 @item * + ? @{@}\n\ |
|
733 Repetition operators, representing\n\ |
|
734 @table @code\n\ |
|
735 @item *\n\ |
|
736 Match zero or more times\n\ |
|
737 @item +\n\ |
|
738 Match one or more times\n\ |
|
739 @item ?\n\ |
|
740 Match zero or one times\n\ |
|
741 @item @{@}\n\ |
|
742 Match range operator, which is of the form @code{@{@var{n}@}} to match exactly\n\ |
|
743 @var{n} times, @code{@{@var{m},@}} to match @var{m} or more times,\n\ |
|
744 @code{@{@var{m},@var{n}@}} to match between @var{m} and @var{n} times.\n\ |
|
745 @end table\n\ |
|
746 @item [@dots{}] [^@dots{}]\n\ |
|
747 List operators, where for example @code{[ab]c} matches @code{ac} and @code{bc}\n\ |
|
748 @item ()\n\ |
|
749 Grouping operator\n\ |
|
750 @item |\n\ |
|
751 Alternation operator. Match one of a choice of regular expressions. The\n\ |
7001
|
752 alternatives must be delimited by the grouping operator @code{()} above\n\ |
5582
|
753 @item ^ $\n\ |
|
754 Anchoring operator. @code{^} matches the start of the string @var{str} and\n\ |
|
755 @code{$} the end\n\ |
|
756 @end table\n\ |
|
757 \n\ |
|
758 In addition the following escaped characters have special meaning. It should\n\ |
|
759 be noted that it is recommended to quote @var{pat} in single quotes rather\n\ |
|
760 than double quotes, to avoid the escape sequences being interpreted by octave\n\ |
|
761 before being passed to @code{regexp}.\n\ |
|
762 \n\ |
|
763 @table @code\n\ |
|
764 @item \\b\n\ |
|
765 Match a word boundary\n\ |
|
766 @item \\B\n\ |
|
767 Match within a word\n\ |
|
768 @item \\w\n\ |
|
769 Matches any word character\n\ |
|
770 @item \\W\n\ |
|
771 Matches any non word character\n\ |
|
772 @item \\<\n\ |
|
773 Matches the beginning of a word\n\ |
|
774 @item \\>\n\ |
|
775 Matches the end of a word\n\ |
|
776 @item \\s\n\ |
|
777 Matches any whitespace character\n\ |
|
778 @item \\S\n\ |
|
779 Matches any non whitespace character\n\ |
|
780 @item \\d\n\ |
|
781 Matches any digit\n\ |
|
782 @item \\D\n\ |
|
783 Matches any non-digit\n\ |
|
784 @end table\n\ |
|
785 \n\ |
|
786 The outputs of @code{regexp} by default are in the order as given below\n\ |
|
787 \n\ |
|
788 @table @asis\n\ |
|
789 @item @var{s}\n\ |
|
790 The start indices of each of the matching substrings\n\ |
|
791 \n\ |
|
792 @item @var{e}\n\ |
|
793 The end indices of each matching substring\n\ |
|
794 \n\ |
|
795 @item @var{te}\n\ |
|
796 The extents of each of the matched token surrounded by @code{(@dots{})} in\n\ |
|
797 @var{pat}.\n\ |
|
798 \n\ |
|
799 @item @var{m}\n\ |
|
800 A cell array of the text of each match.\n\ |
|
801 \n\ |
|
802 @item @var{t}\n\ |
|
803 A cell array of the text of each token matched.\n\ |
|
804 \n\ |
|
805 @item @var{nm}\n\ |
|
806 A structure containing the text of each matched named token, with the name\n\ |
|
807 being used as the fieldname. A named token is denoted as\n\ |
|
808 @code{(?<name>@dots{})}\n\ |
|
809 @end table\n\ |
|
810 \n\ |
|
811 Particular output arguments or the order of the output arguments can be\n\ |
|
812 selected by additional @var{opts} arguments. These are strings and the\n\ |
|
813 correspondence between the output arguments and the optional argument\n\ |
|
814 are\n\ |
|
815 \n\ |
|
816 @multitable @columnfractions 0.2 0.3 0.3 0.2\n\ |
|
817 @item @tab 'start' @tab @var{s} @tab\n\ |
|
818 @item @tab 'end' @tab @var{e} @tab\n\ |
|
819 @item @tab 'tokenExtents' @tab @var{te} @tab\n\ |
|
820 @item @tab 'match' @tab @var{m} @tab\n\ |
|
821 @item @tab 'tokens' @tab @var{t} @tab\n\ |
|
822 @item @tab 'names' @tab @var{nm} @tab\n\ |
|
823 @end multitable\n\ |
|
824 \n\ |
|
825 A further optional argument is 'once', that limits the number of returned\n\ |
5779
|
826 matches to the first match. Additional arguments are\n\ |
|
827 \n\ |
|
828 @table @asis\n\ |
|
829 @item matchcase\n\ |
|
830 Make the matching case sensitive.\n\ |
|
831 @item ignorecase\n\ |
|
832 Make the matching case insensitive.\n\ |
|
833 @item stringanchors\n\ |
|
834 Match the anchor characters at the beginning and end of the string.\n\ |
|
835 @item lineanchors\n\ |
|
836 Match the anchor characters at the beginning and end of the line.\n\ |
|
837 @item dotall\n\ |
|
838 The character @code{.} matches the newline character.\n\ |
|
839 @item dotexceptnewline\n\ |
|
840 The character @code{.} matches all but the newline character.\n\ |
|
841 @item freespacing\n\ |
|
842 The pattern can include arbitrary whitespace and comments starting with\n\ |
|
843 @code{#}.\n\ |
|
844 @item literalspacing\n\ |
|
845 The pattern is taken literally.\n\ |
|
846 @end table\n\ |
5582
|
847 @end deftypefn") |
|
848 { |
6361
|
849 octave_value_list retval; |
|
850 int nargin = args.length(); |
|
851 |
|
852 if (nargin < 2) |
|
853 print_usage (); |
|
854 else if (args(0).is_cell() || args(1).is_cell()) |
|
855 retval = octcellregexp (args, nargout, "regexp", false); |
|
856 else |
|
857 retval = octregexp (args, nargout, "regexp", false); |
|
858 |
|
859 return retval; |
5582
|
860 } |
|
861 |
|
862 /* |
|
863 |
|
864 ## seg-fault test |
|
865 %!assert(regexp("abcde","."),[1,2,3,4,5]) |
|
866 |
|
867 ## Check that anchoring of pattern works correctly |
|
868 %!assert(regexp('abcabc','^abc'),1); |
|
869 %!assert(regexp('abcabc','abc$'),4); |
5785
|
870 %!assert(regexp('abcabc','^abc$'),zeros(1,0)); |
5582
|
871 |
|
872 %!test |
|
873 %! [s, e, te, m, t] = regexp(' No Match ', 'f(.*)uck'); |
5785
|
874 %! assert (s,zeros(1,0)) |
|
875 %! assert (e,zeros(1,0)) |
|
876 %! assert (te,cell(1,0)) |
|
877 %! assert (m, cell(1,0)) |
|
878 %! assert (t, cell(1,0)) |
5582
|
879 |
|
880 %!test |
|
881 %! [s, e, te, m, t] = regexp(' FiRetrUck ', 'f(.*)uck'); |
5785
|
882 %! assert (s,zeros(1,0)) |
|
883 %! assert (e,zeros(1,0)) |
|
884 %! assert (te,cell(1,0)) |
|
885 %! assert (m, cell(1,0)) |
|
886 %! assert (t, cell(1,0)) |
5582
|
887 |
|
888 %!test |
|
889 %! [s, e, te, m, t] = regexp(' firetruck ', 'f(.*)uck'); |
|
890 %! assert (s,2) |
|
891 %! assert (e,10) |
|
892 %! assert (te{1},[3,7]) |
|
893 %! assert (m{1}, 'firetruck') |
|
894 %! assert (t{1}{1}, 'iretr') |
|
895 |
|
896 %!test |
|
897 %! [s, e, te, m, t] = regexp('short test string','\w*r\w*'); |
|
898 %! assert (s,[1,12]) |
|
899 %! assert (e,[5,17]) |
|
900 %! assert (size(te), [1,2]) |
|
901 %! assert (isempty(te{1})) |
|
902 %! assert (isempty(te{2})) |
|
903 %! assert (m{1},'short') |
|
904 %! assert (m{2},'string') |
|
905 %! assert (size(t), [1,2]) |
|
906 %! assert (isempty(t{1})) |
|
907 %! assert (isempty(t{2})) |
|
908 |
|
909 %!test |
|
910 %! [s, e, te, m, t] = regexp('short test string','\w*r\w*','once'); |
|
911 %! assert (s,1) |
|
912 %! assert (e,5) |
|
913 %! assert (size(te), [1,1]) |
|
914 %! assert (isempty(te{1})) |
|
915 %! assert (m{1},'short') |
|
916 %! ## Matlab gives [1,0] here but that seems wrong. |
|
917 %! assert (size(t), [1,1]) |
|
918 |
|
919 %!test |
|
920 %! [m, te, e, s, t] = regexp('short test string','\w*r\w*','once', 'match', 'tokenExtents', 'end', 'start', 'tokens'); |
|
921 %! assert (s,1) |
|
922 %! assert (e,5) |
|
923 %! assert (size(te), [1,1]) |
|
924 %! assert (isempty(te{1})) |
|
925 %! assert (m{1},'short') |
|
926 %! ## Matlab gives [1,0] here but that seems wrong. |
|
927 %! assert (size(t), [1,1]) |
|
928 |
5619
|
929 %!test |
5582
|
930 %! ## This test is expected to fail if PCRE is not installed |
5620
|
931 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
5619
|
932 %! [s, e, te, m, t, nm] = regexp('short test string','(?<word1>\w*t)\s*(?<word2>\w*t)'); |
|
933 %! assert (s,1) |
|
934 %! assert (e,10) |
|
935 %! assert (size(te), [1,1]) |
|
936 %! assert (te{1}, [1 5; 7, 10]) |
|
937 %! assert (m{1},'short test') |
|
938 %! assert (size(t),[1,1]) |
|
939 %! assert (t{1}{1},'short') |
|
940 %! assert (t{1}{2},'test') |
|
941 %! assert (size(nm), [1,1]) |
|
942 %! assert (!isempty(fieldnames(nm))) |
|
943 %! assert (sort(fieldnames(nm)),{'word1';'word2'}) |
|
944 %! assert (nm.word1,'short') |
|
945 %! assert (nm.word2,'test') |
|
946 %! endif |
5582
|
947 |
5619
|
948 %!test |
5582
|
949 %! ## This test is expected to fail if PCRE is not installed |
5620
|
950 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
5619
|
951 %! [nm, m, te, e, s, t] = regexp('short test string','(?<word1>\w*t)\s*(?<word2>\w*t)', 'names', 'match', 'tokenExtents', 'end', 'start', 'tokens'); |
|
952 %! assert (s,1) |
|
953 %! assert (e,10) |
|
954 %! assert (size(te), [1,1]) |
|
955 %! assert (te{1}, [1 5; 7, 10]) |
|
956 %! assert (m{1},'short test') |
|
957 %! assert (size(t),[1,1]) |
|
958 %! assert (t{1}{1},'short') |
|
959 %! assert (t{1}{2},'test') |
|
960 %! assert (size(nm), [1,1]) |
|
961 %! assert (!isempty(fieldnames(nm))) |
|
962 %! assert (sort(fieldnames(nm)),{'word1';'word2'}) |
|
963 %! assert (nm.word1,'short') |
|
964 %! assert (nm.word2,'test') |
|
965 %! endif |
|
966 |
|
967 %!test |
|
968 %! ## This test is expected to fail if PCRE is not installed |
5620
|
969 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
5619
|
970 %! [t, nm] = regexp("John Davis\nRogers, James",'(?<first>\w+)\s+(?<last>\w+)|(?<last>\w+),\s+(?<first>\w+)','tokens','names'); |
|
971 %! assert (size(t), [1,2]); |
|
972 %! assert (t{1}{1},'John'); |
|
973 %! assert (t{1}{2},'Davis'); |
|
974 %! assert (t{2}{1},'Rogers'); |
|
975 %! assert (t{2}{2},'James'); |
|
976 %! assert (size(nm), [1,1]); |
|
977 %! assert (nm.first{1},'John'); |
|
978 %! assert (nm.first{2},'James'); |
|
979 %! assert (nm.last{1},'Davis'); |
|
980 %! assert (nm.last{2},'Rogers'); |
|
981 %! endif |
5582
|
982 |
5779
|
983 %!assert(regexp("abc\nabc",'.'),[1:7]) |
|
984 %!assert(regexp("abc\nabc",'.','dotall'),[1:7]) |
|
985 %!test |
|
986 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
|
987 %! assert(regexp("abc\nabc",'(?s).'),[1:7]) |
|
988 %! assert(regexp("abc\nabc",'.','dotexceptnewline'),[1,2,3,5,6,7]) |
|
989 %! assert(regexp("abc\nabc",'(?-s).'),[1,2,3,5,6,7]) |
|
990 %! endif |
|
991 |
|
992 %!assert(regexp("caseCaSe",'case'),1) |
|
993 %!assert(regexp("caseCaSe",'case',"matchcase"),1) |
|
994 %!assert(regexp("caseCaSe",'case',"ignorecase"),[1,5]) |
|
995 %!test |
|
996 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
|
997 %! assert(regexp("caseCaSe",'(?-i)case'),1) |
|
998 %! assert(regexp("caseCaSe",'(?i)case'),[1,5]) |
|
999 %! endif |
|
1000 |
|
1001 %!assert (regexp("abc\nabc",'c$'),7) |
|
1002 %!assert (regexp("abc\nabc",'c$',"stringanchors"),7) |
|
1003 %!test |
|
1004 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
|
1005 %! assert (regexp("abc\nabc",'(?-m)c$'),7) |
|
1006 %! assert (regexp("abc\nabc",'c$',"lineanchors"),[3,7]) |
|
1007 %! assert (regexp("abc\nabc",'(?m)c$'),[3,7]) |
|
1008 %! endif |
|
1009 |
|
1010 %!assert (regexp("this word",'s w'),4) |
|
1011 %!assert (regexp("this word",'s w','literalspacing'),4) |
|
1012 %!test |
|
1013 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
|
1014 %! assert (regexp("this word",'(?-x)s w','literalspacing'),4) |
5785
|
1015 %! assert (regexp("this word",'s w','freespacing'),zeros(1,0)) |
|
1016 %! assert (regexp("this word",'(?x)s w'),zeros(1,0)) |
5779
|
1017 %! endif |
|
1018 |
5582
|
1019 %!error regexp('string', 'tri', 'BadArg'); |
|
1020 %!error regexp('string'); |
|
1021 |
6361
|
1022 %!assert(regexp({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'},'-'),{6;[1,5,9];zeros(1,0)}) |
|
1023 %!assert(regexp({'asdfg-dfd','-dfd-dfd-','qasfdfdaq'},'-'),{6,[1,5,9],zeros(1,0)}) |
|
1024 %!assert(regexp({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'},{'-';'f';'q'}),{6;[3,7];[1,9]}) |
|
1025 %!assert(regexp('Strings',{'t','s'}),{2,7}) |
|
1026 |
5582
|
1027 */ |
|
1028 |
6549
|
1029 DEFUN_DLD (regexpi, args, nargout, |
5582
|
1030 "-*- texinfo -*-\n\ |
|
1031 @deftypefn {Loadable Function} {[@var{s}, @var{e}, @var{te}, @var{m}, @var{t}, @var{nm}] =} regexpi (@var{str}, @var{pat})\n\ |
|
1032 @deftypefnx {Loadable Function} {[@dots{}] =} regexpi (@var{str}, @var{pat}, @var{opts}, @dots{})\n\ |
|
1033 \n\ |
|
1034 Case insensitive regular expression string matching. Matches @var{pat} in\n\ |
|
1035 @var{str} and returns the position and matching substrings or empty values\n\ |
|
1036 if there are none. See @code{regexp} for more details\n\ |
|
1037 @end deftypefn") |
|
1038 { |
6361
|
1039 octave_value_list retval; |
|
1040 int nargin = args.length(); |
|
1041 |
|
1042 if (nargin < 2) |
|
1043 print_usage (); |
|
1044 else if (args(0).is_cell() || args(1).is_cell()) |
|
1045 retval = octcellregexp (args, nargout, "regexpi", true); |
|
1046 else |
|
1047 retval = octregexp (args, nargout, "regexpi", true); |
|
1048 |
|
1049 return retval; |
5582
|
1050 } |
|
1051 |
|
1052 /* |
|
1053 |
|
1054 ## seg-fault test |
|
1055 %!assert(regexpi("abcde","."),[1,2,3,4,5]) |
|
1056 |
|
1057 ## Check that anchoring of pattern works correctly |
|
1058 %!assert(regexpi('abcabc','^abc'),1); |
|
1059 %!assert(regexpi('abcabc','abc$'),4); |
5785
|
1060 %!assert(regexpi('abcabc','^abc$'),zeros(1,0)); |
5582
|
1061 |
|
1062 %!test |
|
1063 %! [s, e, te, m, t] = regexpi(' No Match ', 'f(.*)uck'); |
5785
|
1064 %! assert (s,zeros(1,0)) |
|
1065 %! assert (e,zeros(1,0)) |
|
1066 %! assert (te,cell(1,0)) |
|
1067 %! assert (m, cell(1,0)) |
|
1068 %! assert (t, cell(1,0)) |
5582
|
1069 |
|
1070 %!test |
|
1071 %! [s, e, te, m, t] = regexpi(' FiRetrUck ', 'f(.*)uck'); |
|
1072 %! assert (s,2) |
|
1073 %! assert (e,10) |
|
1074 %! assert (te{1},[3,7]) |
|
1075 %! assert (m{1}, 'FiRetrUck') |
|
1076 %! assert (t{1}{1}, 'iRetr') |
|
1077 |
|
1078 %!test |
|
1079 %! [s, e, te, m, t] = regexpi(' firetruck ', 'f(.*)uck'); |
|
1080 %! assert (s,2) |
|
1081 %! assert (e,10) |
|
1082 %! assert (te{1},[3,7]) |
|
1083 %! assert (m{1}, 'firetruck') |
|
1084 %! assert (t{1}{1}, 'iretr') |
|
1085 |
|
1086 %!test |
|
1087 %! [s, e, te, m, t] = regexpi('ShoRt Test String','\w*r\w*'); |
|
1088 %! assert (s,[1,12]) |
|
1089 %! assert (e,[5,17]) |
|
1090 %! assert (size(te), [1,2]) |
|
1091 %! assert (isempty(te{1})) |
|
1092 %! assert (isempty(te{2})) |
|
1093 %! assert (m{1},'ShoRt') |
|
1094 %! assert (m{2},'String') |
|
1095 %! assert (size(t), [1,2]) |
|
1096 %! assert (isempty(t{1})) |
|
1097 %! assert (isempty(t{2})) |
|
1098 |
|
1099 %!test |
|
1100 %! [s, e, te, m, t] = regexpi('ShoRt Test String','\w*r\w*','once'); |
|
1101 %! assert (s,1) |
|
1102 %! assert (e,5) |
|
1103 %! assert (size(te), [1,1]) |
|
1104 %! assert (isempty(te{1})) |
|
1105 %! assert (m{1},'ShoRt') |
|
1106 %! ## Matlab gives [1,0] here but that seems wrong. |
|
1107 %! assert (size(t), [1,1]) |
|
1108 |
|
1109 %!test |
|
1110 %! [m, te, e, s, t] = regexpi('ShoRt Test String','\w*r\w*','once', 'match', 'tokenExtents', 'end', 'start', 'tokens'); |
|
1111 %! assert (s,1) |
|
1112 %! assert (e,5) |
|
1113 %! assert (size(te), [1,1]) |
|
1114 %! assert (isempty(te{1})) |
|
1115 %! assert (m{1},'ShoRt') |
|
1116 %! ## Matlab gives [1,0] here but that seems wrong. |
|
1117 %! assert (size(t), [1,1]) |
|
1118 |
5619
|
1119 %!test |
5582
|
1120 %! ## This test is expected to fail if PCRE is not installed |
5620
|
1121 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
5619
|
1122 %! [s, e, te, m, t, nm] = regexpi('ShoRt Test String','(?<word1>\w*t)\s*(?<word2>\w*t)'); |
|
1123 %! assert (s,1) |
|
1124 %! assert (e,10) |
|
1125 %! assert (size(te), [1,1]) |
|
1126 %! assert (te{1}, [1 5; 7, 10]) |
|
1127 %! assert (m{1},'ShoRt Test') |
|
1128 %! assert (size(t),[1,1]) |
|
1129 %! assert (t{1}{1},'ShoRt') |
|
1130 %! assert (t{1}{2},'Test') |
|
1131 %! assert (size(nm), [1,1]) |
|
1132 %! assert (!isempty(fieldnames(nm))) |
|
1133 %! assert (sort(fieldnames(nm)),{'word1';'word2'}) |
|
1134 %! assert (nm.word1,'ShoRt') |
|
1135 %! assert (nm.word2,'Test') |
|
1136 %! endif |
5582
|
1137 |
5619
|
1138 %!test |
5582
|
1139 %! ## This test is expected to fail if PCRE is not installed |
5620
|
1140 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
5619
|
1141 %! [nm, m, te, e, s, t] = regexpi('ShoRt Test String','(?<word1>\w*t)\s*(?<word2>\w*t)', 'names', 'match', 'tokenExtents', 'end', 'start', 'tokens'); |
|
1142 %! assert (s,1) |
|
1143 %! assert (e,10) |
|
1144 %! assert (size(te), [1,1]) |
|
1145 %! assert (te{1}, [1 5; 7, 10]) |
|
1146 %! assert (m{1},'ShoRt Test') |
|
1147 %! assert (size(t),[1,1]) |
|
1148 %! assert (t{1}{1},'ShoRt') |
|
1149 %! assert (t{1}{2},'Test') |
|
1150 %! assert (size(nm), [1,1]) |
|
1151 %! assert (!isempty(fieldnames(nm))) |
|
1152 %! assert (sort(fieldnames(nm)),{'word1';'word2'}) |
|
1153 %! assert (nm.word1,'ShoRt') |
|
1154 %! assert (nm.word2,'Test') |
|
1155 %! endif |
5582
|
1156 |
5779
|
1157 %!assert(regexpi("abc\nabc",'.'),[1:7]) |
|
1158 %!assert(regexpi("abc\nabc",'.','dotall'),[1:7]) |
|
1159 %!test |
|
1160 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
|
1161 %! assert(regexpi("abc\nabc",'(?s).'),[1:7]) |
|
1162 %! assert(regexpi("abc\nabc",'.','dotexceptnewline'),[1,2,3,5,6,7]) |
|
1163 %! assert(regexpi("abc\nabc",'(?-s).'),[1,2,3,5,6,7]) |
|
1164 %! endif |
|
1165 |
|
1166 %!assert(regexpi("caseCaSe",'case'),[1,5]) |
|
1167 %!assert(regexpi("caseCaSe",'case',"matchcase"),1) |
|
1168 %!assert(regexpi("caseCaSe",'case',"ignorecase"),[1,5]) |
|
1169 %!test |
|
1170 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
|
1171 %! assert(regexpi("caseCaSe",'(?-i)case'),1) |
|
1172 %! assert(regexpi("caseCaSe",'(?i)case'),[1,5]) |
|
1173 %! endif |
|
1174 |
|
1175 %!assert (regexpi("abc\nabc",'c$'),7) |
|
1176 %!assert (regexpi("abc\nabc",'c$',"stringanchors"),7) |
|
1177 %!test |
|
1178 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
|
1179 %! assert (regexpi("abc\nabc",'(?-m)c$'),7) |
|
1180 %! assert (regexpi("abc\nabc",'c$',"lineanchors"),[3,7]) |
|
1181 %! assert (regexpi("abc\nabc",'(?m)c$'),[3,7]) |
|
1182 %! endif |
|
1183 |
|
1184 %!assert (regexpi("this word",'s w'),4) |
|
1185 %!assert (regexpi("this word",'s w','literalspacing'),4) |
|
1186 %!test |
|
1187 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
|
1188 %! assert (regexpi("this word",'(?-x)s w','literalspacing'),4) |
5785
|
1189 %! assert (regexpi("this word",'s w','freespacing'),zeros(1,0)) |
|
1190 %! assert (regexpi("this word",'(?x)s w'),zeros(1,0)) |
5779
|
1191 %! endif |
|
1192 |
5582
|
1193 %!error regexpi('string', 'tri', 'BadArg'); |
|
1194 %!error regexpi('string'); |
|
1195 |
6361
|
1196 %!assert(regexpi({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'},'-'),{6;[1,5,9];zeros(1,0)}) |
|
1197 %!assert(regexpi({'asdfg-dfd','-dfd-dfd-','qasfdfdaq'},'-'),{6,[1,5,9],zeros(1,0)}) |
|
1198 %!assert(regexpi({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'},{'-';'f';'q'}),{6;[3,7];[1,9]}) |
|
1199 %!assert(regexpi('Strings',{'t','s'}),{2,[1,7]}) |
|
1200 |
5582
|
1201 */ |
|
1202 |
6361
|
1203 |
|
1204 static octave_value |
|
1205 octregexprep (const octave_value_list &args, const std::string &nm) |
5785
|
1206 { |
6361
|
1207 octave_value retval; |
5785
|
1208 int nargin = args.length(); |
|
1209 |
|
1210 // Make sure we have string,pattern,replacement |
|
1211 const std::string buffer = args(0).string_value (); |
|
1212 if (error_state) return retval; |
|
1213 const std::string pattern = args(1).string_value (); |
|
1214 if (error_state) return retval; |
|
1215 const std::string replacement = args(2).string_value (); |
|
1216 if (error_state) return retval; |
|
1217 |
|
1218 // Pack options excluding 'tokenize' and various output |
|
1219 // reordering strings into regexp arg list |
|
1220 octave_value_list regexpargs(nargin-1,octave_value()); |
|
1221 regexpargs(0) = args(0); |
|
1222 regexpargs(1) = args(1); |
|
1223 int len=2; |
|
1224 for (int i = 3; i < nargin; i++) |
|
1225 { |
|
1226 const std::string opt = args(i).string_value(); |
|
1227 if (opt != "tokenize" && opt != "start" && opt != "end" |
|
1228 && opt != "tokenextents" && opt != "match" && opt != "tokens" |
|
1229 && opt != "names" && opt != "warnings") |
|
1230 { |
|
1231 regexpargs(len++) = args(i); |
|
1232 } |
|
1233 } |
|
1234 regexpargs.resize(len); |
|
1235 |
|
1236 // Identify replacement tokens; build a vector of group numbers in |
|
1237 // the replacement string so that we can quickly calculate the size |
|
1238 // of the replacement. |
|
1239 int tokens = 0; |
|
1240 for (size_t i=1; i < replacement.size(); i++) |
|
1241 { |
|
1242 if (replacement[i-1]=='$' && isdigit(replacement[i])) |
|
1243 { |
|
1244 tokens++, i++; |
|
1245 } |
|
1246 } |
|
1247 std::vector<int> token(tokens); |
|
1248 int kk = 0; |
|
1249 for (size_t i = 1; i < replacement.size(); i++) |
|
1250 { |
|
1251 if (replacement[i-1]=='$' && isdigit(replacement[i])) |
|
1252 { |
|
1253 token[kk++] = replacement[i]-'0'; |
|
1254 i++; |
|
1255 } |
|
1256 } |
|
1257 |
|
1258 // Perform replacement |
|
1259 std::string rep; |
|
1260 if (tokens > 0) |
|
1261 { |
|
1262 std::list<regexp_elem> lst; |
|
1263 string_vector named; |
|
1264 int nopts; |
6361
|
1265 int sz = octregexp_list (regexpargs, nm , false, lst, named, nopts); |
5785
|
1266 |
|
1267 if (error_state) |
|
1268 return retval; |
|
1269 if (sz == 0) |
|
1270 { |
6361
|
1271 retval = args(0); |
5785
|
1272 return retval; |
|
1273 } |
|
1274 |
|
1275 // Determine replacement length |
|
1276 const size_t replen = replacement.size() - 2*tokens; |
|
1277 int delta = 0; |
|
1278 const_iterator p = lst.begin(); |
|
1279 for (int i = 0; i < sz; i++) |
|
1280 { |
|
1281 OCTAVE_QUIT; |
|
1282 |
|
1283 const Matrix pairs(p->te); |
|
1284 size_t pairlen = 0; |
|
1285 for (int j = 0; j < tokens; j++) |
|
1286 { |
|
1287 if (token[j] == 0) |
|
1288 pairlen += static_cast<size_t>(p->e - p->s) + 1; |
|
1289 else if (token[j] <= pairs.rows()) |
|
1290 pairlen += static_cast<size_t>(pairs(token[j]-1,1) - |
|
1291 pairs(token[j]-1,0)) + 1; |
|
1292 } |
|
1293 delta += static_cast<int>(replen + pairlen) - |
|
1294 static_cast<int>(p->e - p->s + 1); |
|
1295 p++; |
|
1296 } |
|
1297 |
|
1298 // Build replacement string |
|
1299 rep.reserve(buffer.size()+delta); |
|
1300 size_t from = 0; |
|
1301 p = lst.begin(); |
|
1302 for (int i=0; i < sz; i++) |
|
1303 { |
|
1304 OCTAVE_QUIT; |
|
1305 |
|
1306 const Matrix pairs(p->te); |
|
1307 rep.append(&buffer[from], static_cast<size_t>(p->s - 1) - from); |
|
1308 from = static_cast<size_t>(p->e - 1) + 1; |
|
1309 for (size_t j = 1; j < replacement.size(); j++) |
|
1310 { |
|
1311 if (replacement[j-1]=='$' && isdigit(replacement[j])) |
|
1312 { |
|
1313 int k = replacement[j]-'0'; |
|
1314 if (k == 0) |
|
1315 { |
|
1316 // replace with entire match |
|
1317 rep.append(&buffer[static_cast<size_t>(p->e - 1)], |
|
1318 static_cast<size_t>(p->e - p->s) + 1); |
|
1319 } |
|
1320 else if (k <= pairs.rows()) |
|
1321 { |
|
1322 // replace with group capture |
|
1323 rep.append(&buffer[static_cast<size_t>(pairs(k-1,0)-1)], |
|
1324 static_cast<size_t>(pairs(k-1,1) - |
|
1325 pairs(k-1,0))+1); |
|
1326 } |
|
1327 else |
|
1328 { |
|
1329 // replace with nothing |
|
1330 } |
|
1331 j++; |
|
1332 } |
|
1333 else |
|
1334 { |
|
1335 rep.append(1,replacement[j-1]); |
|
1336 } |
|
1337 if (j+1 == replacement.size()) |
|
1338 { |
|
1339 rep.append(1,replacement[j]); |
|
1340 } |
|
1341 } |
|
1342 p++; |
|
1343 } |
|
1344 rep.append(&buffer[from],buffer.size()-from); |
|
1345 } |
|
1346 else |
|
1347 { |
|
1348 std::list<regexp_elem> lst; |
|
1349 string_vector named; |
|
1350 int nopts; |
6361
|
1351 int sz = octregexp_list (regexpargs, nm, false, lst, named,nopts); |
5785
|
1352 |
|
1353 if (error_state) |
|
1354 return retval; |
|
1355 if (sz == 0) |
|
1356 { |
6361
|
1357 retval = args(0); |
5785
|
1358 return retval; |
|
1359 } |
|
1360 |
|
1361 // Determine replacement length |
|
1362 const size_t replen = replacement.size(); |
|
1363 int delta = 0; |
|
1364 const_iterator p = lst.begin(); |
|
1365 for (int i = 0; i < sz; i++) |
|
1366 { |
|
1367 OCTAVE_QUIT; |
|
1368 delta += static_cast<int>(replen) - |
|
1369 static_cast<int>(p->e - p->s + 1); |
|
1370 p++; |
|
1371 } |
|
1372 |
|
1373 // Build replacement string |
|
1374 rep.reserve(buffer.size()+delta); |
|
1375 size_t from = 0; |
|
1376 p = lst.begin(); |
|
1377 for (int i=0; i < sz; i++) |
|
1378 { |
|
1379 OCTAVE_QUIT; |
|
1380 rep.append(&buffer[from], static_cast<size_t>(p->s - 1) - from); |
|
1381 from = static_cast<size_t>(p->e - 1) + 1; |
|
1382 rep.append(replacement); |
|
1383 p++; |
|
1384 } |
|
1385 rep.append(&buffer[from],buffer.size()-from); |
|
1386 } |
|
1387 |
6361
|
1388 retval = rep; |
|
1389 return retval; |
|
1390 } |
|
1391 |
6549
|
1392 DEFUN_DLD (regexprep, args, , |
6361
|
1393 "-*- texinfo -*-\n\ |
6678
|
1394 @deftypefn {Loadable Function} {@var{string} =} regexprep (@var{string}, @var{pat}, @var{repstr}, @var{options})\n\ |
6361
|
1395 Replace matches of @var{pat} in @var{string} with @var{repstr}.\n\ |
|
1396 \n\ |
|
1397 \n\ |
7007
|
1398 The replacement can contain @code{$i}, which substitutes\n\ |
6361
|
1399 for the ith set of parentheses in the match string. E.g.,\n\ |
|
1400 @example\n\ |
|
1401 \n\ |
|
1402 regexprep(\"Bill Dunn\",'(\\w+) (\\w+)','$2, $1')\n\ |
|
1403 \n\ |
|
1404 @end example\n\ |
|
1405 returns \"Dunn, Bill\"\n\ |
|
1406 \n\ |
|
1407 @var{options} may be zero or more of\n\ |
|
1408 @table @samp\n\ |
|
1409 \n\ |
|
1410 @item once\n\ |
7001
|
1411 Replace only the first occurrence of @var{pat} in the result.\n\ |
6361
|
1412 \n\ |
|
1413 @item warnings\n\ |
|
1414 This option is present for compatibility but is ignored.\n\ |
|
1415 \n\ |
|
1416 @item ignorecase or matchcase\n\ |
|
1417 Ignore case for the pattern matching (see @code{regexpi}).\n\ |
|
1418 Alternatively, use (?i) or (?-i) in the pattern.\n\ |
|
1419 \n\ |
|
1420 @item lineanchors and stringanchors\n\ |
|
1421 Whether characters ^ and $ match the beginning and ending of lines.\n\ |
|
1422 Alternatively, use (?m) or (?-m) in the pattern.\n\ |
|
1423 \n\ |
|
1424 @item dotexceptnewline and dotall\n\ |
|
1425 Whether . matches newlines in the string.\n\ |
|
1426 Alternatively, use (?s) or (?-s) in the pattern.\n\ |
|
1427 \n\ |
|
1428 @item freespacing or literalspacing\n\ |
|
1429 Whether whitespace and # comments can be used to make the regular expression more readable.\n\ |
|
1430 Alternatively, use (?x) or (?-x) in the pattern.\n\ |
|
1431 \n\ |
|
1432 @end table\n\ |
|
1433 @seealso{regexp,regexpi}\n\ |
|
1434 @end deftypefn") |
|
1435 { |
|
1436 octave_value_list retval; |
|
1437 int nargin = args.length(); |
|
1438 |
|
1439 if (nargin < 3) |
|
1440 { |
|
1441 print_usage (); |
|
1442 return retval; |
|
1443 } |
|
1444 |
|
1445 if (args(0).is_cell() || args(1).is_cell() || args(2).is_cell()) |
|
1446 { |
|
1447 Cell str; |
|
1448 Cell pat; |
|
1449 Cell rep; |
6495
|
1450 dim_vector dv0; |
|
1451 dim_vector dv1(1,1); |
6361
|
1452 |
|
1453 if (args(0).is_cell()) |
|
1454 str = args(0).cell_value(); |
|
1455 else |
|
1456 str = Cell (args(0)); |
|
1457 |
|
1458 if (args(1).is_cell()) |
|
1459 pat = args(1).cell_value(); |
|
1460 else |
|
1461 pat = Cell (args(1)); |
|
1462 |
|
1463 if (args(2).is_cell()) |
|
1464 rep = args(2).cell_value(); |
|
1465 else |
|
1466 rep = Cell (args(2)); |
|
1467 |
6495
|
1468 dv0 = str.dims(); |
|
1469 if (pat.numel() != 1) |
6361
|
1470 { |
6495
|
1471 dv1 = pat.dims(); |
|
1472 if (rep.numel() != 1 && dv1 != rep.dims()) |
6361
|
1473 error ("regexprep: Inconsistent cell array dimensions"); |
|
1474 } |
|
1475 else if (rep.numel() != 1) |
6495
|
1476 dv1 = rep.dims(); |
6361
|
1477 |
|
1478 if (!error_state) |
|
1479 { |
6495
|
1480 Cell ret (dv0); |
6361
|
1481 octave_value_list new_args = args; |
|
1482 |
6495
|
1483 for (octave_idx_type i = 0; i < dv0.numel(); i++) |
|
1484 { |
|
1485 new_args(0) = str(i); |
|
1486 if (pat.numel() == 1) |
|
1487 new_args(1) = pat(0); |
|
1488 if (rep.numel() == 1) |
|
1489 new_args(2) = rep(0); |
|
1490 for (octave_idx_type j = 0; j < dv1.numel(); j++) |
|
1491 { |
|
1492 if (pat.numel() != 1) |
|
1493 new_args(1) = pat(j); |
|
1494 if (rep.numel() != 1) |
|
1495 new_args(2) = rep(j); |
|
1496 new_args(0) = octregexprep (new_args, "regexprep"); |
6361
|
1497 |
6495
|
1498 if (error_state) |
|
1499 break; |
|
1500 } |
6361
|
1501 |
|
1502 if (error_state) |
|
1503 break; |
6495
|
1504 |
|
1505 ret(i) = new_args(0); |
6361
|
1506 } |
|
1507 |
|
1508 if (!error_state) |
|
1509 retval = octave_value (ret); |
|
1510 } |
|
1511 } |
|
1512 else |
|
1513 retval = octregexprep (args, "regexprep"); |
|
1514 |
5785
|
1515 return retval; |
|
1516 } |
|
1517 |
|
1518 /* |
|
1519 %!test # Replace with empty |
|
1520 %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>'; |
|
1521 %! t = regexprep(xml,'<[!?][^>]*>',''); |
|
1522 %! assert(t,' <tag v="hello">some stuff</tag>') |
|
1523 |
|
1524 %!test # Replace with non-empty |
|
1525 %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>'; |
|
1526 %! t = regexprep(xml,'<[!?][^>]*>','?'); |
|
1527 %! assert(t,'? <tag v="hello">some stuff?</tag>') |
|
1528 |
|
1529 %!test # Check that 'tokenize' is ignored |
|
1530 %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>'; |
|
1531 %! t = regexprep(xml,'<[!?][^>]*>','','tokenize'); |
|
1532 %! assert(t,' <tag v="hello">some stuff</tag>') |
|
1533 |
|
1534 %!test # Capture replacement |
|
1535 %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) |
|
1536 %! data = "Bob Smith\nDavid Hollerith\nSam Jenkins"; |
|
1537 %! result = "Smith, Bob\nHollerith, David\nJenkins, Sam"; |
|
1538 %! t = regexprep(data,'(?m)^(\w+)\s+(\w+)$','$2, $1'); |
|
1539 %! assert(t,result) |
|
1540 %! end |
|
1541 |
|
1542 # Return the original if no match |
|
1543 %!assert(regexprep('hello','world','earth'),'hello') |
|
1544 |
|
1545 ## Test a general replacement |
|
1546 %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Za-z0-9_]", "_"), "a_b_c_d_e_f_g"); |
|
1547 |
|
1548 ## Make sure it works at the beginning and end |
|
1549 %!assert(regexprep("a[b]c{d}e-f=g", "a", "_"), "_[b]c{d}e-f=g"); |
|
1550 %!assert(regexprep("a[b]c{d}e-f=g", "g", "_"), "a[b]c{d}e-f=_"); |
|
1551 |
|
1552 ## Options |
|
1553 %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Za-z0-9_]", "_", "once"), "a_b]c{d}e-f=g"); |
|
1554 %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Z0-9_]", "_", "ignorecase"), "a_b_c_d_e_f_g"); |
|
1555 |
|
1556 ## Option combinations |
|
1557 %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Z0-9_]", "_", "once", "ignorecase"), "a_b]c{d}e-f=g"); |
|
1558 |
|
1559 ## End conditions on replacement |
|
1560 %!assert(regexprep("abc","(b)",".$1"),"a.bc"); |
|
1561 %!assert(regexprep("abc","(b)","$1"),"abc"); |
|
1562 %!assert(regexprep("abc","(b)","$1."),"ab.c"); |
|
1563 %!assert(regexprep("abc","(b)","$1.."),"ab..c"); |
|
1564 |
6361
|
1565 ## Test cell array arguments |
6503
|
1566 %!assert(regexprep("abc",{"b","a"},"?"),{"??c"}) |
6361
|
1567 %!assert(regexprep({"abc","cba"},"b","?"),{"a?c","c?a"}) |
6503
|
1568 %!assert(regexprep({"abc","cba"},{"b","a"},{"?","!"}),{"!?c","c?!"}) |
6361
|
1569 |
5785
|
1570 */ |
|
1571 |
5582
|
1572 /* |
|
1573 ;;; Local Variables: *** |
|
1574 ;;; mode: C++ *** |
|
1575 ;;; End: *** |
|
1576 */ |