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