1 /**********************************************************************
6 created at: Mon Aug 9 18:24:49 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "ruby/ruby.h"
14 #include "ruby/encoding.h"
15 #include "ruby/util.h"
19 VALUE rb_eRegexpError
;
21 typedef char onig_errmsg_buffer
[ONIG_MAX_ERROR_MESSAGE_LEN
];
23 #define BEG(no) regs->beg[no]
24 #define END(no) regs->end[no]
26 #if 'a' == 97 /* it's ascii */
27 static const char casetable
[] = {
28 '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
29 '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
30 '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
31 '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
32 /* ' ' '!' '"' '#' '$' '%' '&' ''' */
33 '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
34 /* '(' ')' '*' '+' ',' '-' '.' '/' */
35 '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
36 /* '0' '1' '2' '3' '4' '5' '6' '7' */
37 '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
38 /* '8' '9' ':' ';' '<' '=' '>' '?' */
39 '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
40 /* '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G' */
41 '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
42 /* 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' */
43 '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
44 /* 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' */
45 '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
46 /* 'X' 'Y' 'Z' '[' '\' ']' '^' '_' */
47 '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
48 /* '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g' */
49 '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
50 /* 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' */
51 '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
52 /* 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' */
53 '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
54 /* 'x' 'y' 'z' '{' '|' '}' '~' */
55 '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
56 '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
57 '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
58 '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
59 '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
60 '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
61 '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
62 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
63 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
64 '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
65 '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
66 '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
67 '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
68 '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
69 '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
70 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
71 '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377',
74 # error >>> "You lose. You will need a translation table for your character set." <<<
78 rb_memcicmp(const void *x
, const void *y
, long len
)
80 const unsigned char *p1
= x
, *p2
= y
;
84 if ((tmp
= casetable
[(unsigned)*p1
++] - casetable
[(unsigned)*p2
++]))
93 rb_memcmp(const void *p1
, const void *p2
, long len
)
95 return memcmp(p1
, p2
, len
);
99 rb_memsearch_ss(const unsigned char *xs
, long m
, const unsigned char *ys
, long n
)
101 const unsigned char *x
= xs
, *xe
= xs
+ m
;
102 const unsigned char *y
= ys
, *ye
= ys
+ n
;
104 # if SIZEOF_VALUE == 8
105 # define VALUE_MAX 0xFFFFFFFFFFFFFFFFULL
106 # elif SIZEOF_VALUE == 4
107 # define VALUE_MAX 0xFFFFFFFFUL
110 VALUE hx
, hy
, mask
= VALUE_MAX
>> ((SIZEOF_VALUE
- m
) * CHAR_BIT
);
112 if (m
> SIZEOF_VALUE
)
113 rb_bug("!!too long pattern string!!");
115 /* Prepare hash value */
116 for (hx
= *x
++, hy
= *y
++; x
< xe
; ++x
, ++y
) {
135 rb_memsearch_qs(const unsigned char *xs
, long m
, const unsigned char *ys
, long n
)
137 const unsigned char *x
= xs
, *xe
= xs
+ m
;
138 const unsigned char *y
= ys
;
139 VALUE i
, qstable
[256];
142 for (i
= 0; i
< 256; ++i
)
145 qstable
[*x
] = xe
- x
;
147 for (; y
+ m
<= ys
+ n
; y
+= *(qstable
+ y
[m
])) {
148 if (*xs
== *y
&& memcmp(xs
, y
, m
) == 0)
154 static inline unsigned int
155 rb_memsearch_qs_utf8_hash(const unsigned char *x
)
157 register const unsigned int mix
= 8353;
158 register unsigned int h
= *x
;
183 return (unsigned char)h
;
187 rb_memsearch_qs_utf8(const unsigned char *xs
, long m
, const unsigned char *ys
, long n
)
189 const unsigned char *x
= xs
, *xe
= xs
+ m
;
190 const unsigned char *y
= ys
;
191 VALUE i
, qstable
[512];
194 for (i
= 0; i
< 512; ++i
) {
197 for (; x
< xe
; ++x
) {
198 qstable
[rb_memsearch_qs_utf8_hash(x
)] = xe
- x
;
201 for (; y
+ m
<= ys
+ n
; y
+= qstable
[rb_memsearch_qs_utf8_hash(y
+m
)]) {
202 if (*xs
== *y
&& memcmp(xs
, y
, m
) == 0)
209 rb_memsearch(const void *x0
, long m
, const void *y0
, long n
, rb_encoding
*enc
)
211 const unsigned char *x
= x0
, *y
= y0
;
213 if (m
> n
) return -1;
215 return memcmp(x0
, y0
, m
) == 0 ? 0 : -1;
221 const unsigned char *ys
= y
, *ye
= ys
+ n
;
222 for (; y
< ye
; ++y
) {
228 else if (m
<= SIZEOF_VALUE
) {
229 return rb_memsearch_ss(x0
, m
, y0
, n
);
231 else if (enc
== rb_utf8_encoding()){
232 return rb_memsearch_qs_utf8(x0
, m
, y0
, n
);
235 return rb_memsearch_qs(x0
, m
, y0
, n
);
239 #define REG_LITERAL FL_USER5
240 #define REG_ENCODING_NONE FL_USER6
242 #define KCODE_FIXED FL_USER4
244 #define ARG_REG_OPTION_MASK \
245 (ONIG_OPTION_IGNORECASE|ONIG_OPTION_MULTILINE|ONIG_OPTION_EXTEND)
246 #define ARG_ENCODING_FIXED 16
247 #define ARG_ENCODING_NONE 32
250 char_to_option(int c
)
256 val
= ONIG_OPTION_IGNORECASE
;
259 val
= ONIG_OPTION_EXTEND
;
262 val
= ONIG_OPTION_MULTILINE
;
272 option_to_str(char str
[4], int options
)
275 if (options
& ONIG_OPTION_MULTILINE
) *p
++ = 'm';
276 if (options
& ONIG_OPTION_IGNORECASE
) *p
++ = 'i';
277 if (options
& ONIG_OPTION_EXTEND
) *p
++ = 'x';
283 rb_char_to_option_kcode(int c
, int *option
, int *kcode
)
290 return (*option
= ARG_ENCODING_NONE
);
292 *kcode
= rb_enc_find_index("EUC-JP");
295 *kcode
= rb_enc_find_index("Windows-31J");
298 *kcode
= rb_enc_find_index("UTF-8");
302 return (*option
= char_to_option(c
));
304 *option
= ARG_ENCODING_FIXED
;
309 rb_reg_check(VALUE re
)
311 if (!RREGEXP(re
)->ptr
|| !RREGEXP_SRC(re
) || !RREGEXP_SRC_PTR(re
)) {
312 rb_raise(rb_eTypeError
, "uninitialized Regexp");
317 rb_reg_expr_str(VALUE str
, const char *s
, long len
)
319 rb_encoding
*enc
= rb_enc_get(str
);
320 const char *p
, *pend
;
324 p
= s
; pend
= p
+ len
;
326 c
= rb_enc_ascget(p
, pend
, &clen
, enc
);
328 p
+= mbclen(p
, pend
, enc
);
330 else if (c
!= '/' && rb_enc_isprint(c
, enc
)) {
339 rb_str_buf_cat(str
, s
, len
);
344 c
= rb_enc_ascget(p
, pend
, &clen
, enc
);
345 if (c
== '\\' && p
+clen
< pend
) {
346 int n
= clen
+ mbclen(p
+clen
, pend
, enc
);
347 rb_str_buf_cat(str
, p
, n
);
353 rb_str_buf_cat(str
, &c
, 1);
354 rb_str_buf_cat(str
, p
, clen
);
357 int l
= mbclen(p
, pend
, enc
);
358 rb_str_buf_cat(str
, p
, l
);
362 else if (rb_enc_isprint(c
, enc
)) {
363 rb_str_buf_cat(str
, p
, clen
);
365 else if (!rb_enc_isspace(c
, enc
)) {
368 sprintf(b
, "\\x%02X", c
);
369 rb_str_buf_cat(str
, b
, 4);
372 rb_str_buf_cat(str
, p
, clen
);
380 rb_reg_desc(const char *s
, long len
, VALUE re
)
382 VALUE str
= rb_str_buf_new2("/");
384 rb_enc_copy(str
, re
);
385 rb_reg_expr_str(str
, s
, len
);
386 rb_str_buf_cat2(str
, "/");
390 if (*option_to_str(opts
, RREGEXP(re
)->ptr
->options
))
391 rb_str_buf_cat2(str
, opts
);
402 * Returns the original string of the pattern.
404 * /ab+c/ix.source #=> "ab+c"
406 * Note that escape sequences are retained as is.
408 * /\x20\+/.source #=> "\\x20\\+"
413 rb_reg_source(VALUE re
)
418 str
= rb_enc_str_new(RREGEXP_SRC_PTR(re
),RREGEXP_SRC_LEN(re
), rb_enc_get(re
));
419 if (OBJ_TAINTED(re
)) OBJ_TAINT(str
);
425 * rxp.inspect => string
427 * Produce a nicely formatted string-version of _rxp_. Perhaps surprisingly,
428 * <code>#inspect</code> actually produces the more natural version of
429 * the string than <code>#to_s</code>.
431 * /ab+c/ix.inspect #=> "/ab+c/ix"
436 rb_reg_inspect(VALUE re
)
439 return rb_reg_desc(RREGEXP_SRC_PTR(re
), RREGEXP_SRC_LEN(re
), re
);
447 * Returns a string containing the regular expression and its options (using the
448 * <code>(?opts:source)</code> notation. This string can be fed back in to
449 * <code>Regexp::new</code> to a regular expression with the same semantics as
450 * the original. (However, <code>Regexp#==</code> may not return true when
451 * comparing the two, as the source of the regular expression itself may
452 * differ, as the example shows). <code>Regexp#inspect</code> produces a
453 * generally more readable version of <i>rxp</i>.
455 * r1 = /ab+c/ix #=> /ab+c/ix
456 * s1 = r1.to_s #=> "(?ix-m:ab+c)"
457 * r2 = Regexp.new(s1) #=> /(?ix-m:ab+c)/
459 * r1.source #=> "ab+c"
460 * r2.source #=> "(?ix-m:ab+c)"
464 rb_reg_to_s(VALUE re
)
467 const int embeddable
= ONIG_OPTION_MULTILINE
|ONIG_OPTION_IGNORECASE
|ONIG_OPTION_EXTEND
;
470 VALUE str
= rb_str_buf_new2("(?");
475 rb_enc_copy(str
, re
);
476 options
= RREGEXP(re
)->ptr
->options
;
477 ptr
= (UChar
*)RREGEXP_SRC_PTR(re
);
478 len
= RREGEXP_SRC_LEN(re
);
480 if (len
>= 4 && ptr
[0] == '(' && ptr
[1] == '?') {
483 if ((len
-= 2) > 0) {
485 opt
= char_to_option((int )*ptr
);
495 if (len
> 1 && *ptr
== '-') {
499 opt
= char_to_option((int )*ptr
);
514 if (*ptr
== ':' && ptr
[len
-1] == ')') {
517 r
= onig_alloc_init(&rp
, ONIG_OPTION_DEFAULT
,
518 ONIGENC_CASE_FOLD_DEFAULT
,
524 err
= (onig_compile(rp
, ptr
, ptr
+ len
, NULL
) != 0);
529 options
= RREGEXP(re
)->ptr
->options
;
530 ptr
= (UChar
*)RREGEXP_SRC_PTR(re
);
531 len
= RREGEXP_SRC_LEN(re
);
535 if (*option_to_str(optbuf
, options
)) rb_str_buf_cat2(str
, optbuf
);
537 if ((options
& embeddable
) != embeddable
) {
539 option_to_str(optbuf
+ 1, ~options
);
540 rb_str_buf_cat2(str
, optbuf
);
543 rb_str_buf_cat2(str
, ":");
544 rb_reg_expr_str(str
, (char*)ptr
, len
);
545 rb_str_buf_cat2(str
, ")");
546 rb_enc_copy(str
, re
);
553 rb_reg_raise(const char *s
, long len
, const char *err
, VALUE re
)
555 VALUE desc
= rb_reg_desc(s
, len
, re
);
557 rb_raise(rb_eRegexpError
, "%s: %s", err
, RSTRING_PTR(desc
));
561 rb_enc_reg_error_desc(const char *s
, long len
, rb_encoding
*enc
, int options
, const char *err
)
564 VALUE desc
= rb_str_buf_new2(err
);
566 rb_enc_associate(desc
, enc
);
567 rb_str_buf_cat2(desc
, ": /");
568 rb_reg_expr_str(desc
, s
, len
);
570 option_to_str(opts
+ 1, options
);
571 rb_str_buf_cat2(desc
, opts
);
572 return rb_exc_new3(rb_eRegexpError
, desc
);
576 rb_enc_reg_raise(const char *s
, long len
, rb_encoding
*enc
, int options
, const char *err
)
578 rb_exc_raise(rb_enc_reg_error_desc(s
, len
, enc
, options
, err
));
582 rb_reg_error_desc(VALUE str
, int options
, const char *err
)
584 return rb_enc_reg_error_desc(RSTRING_PTR(str
), RSTRING_LEN(str
),
585 rb_enc_get(str
), options
, err
);
589 rb_reg_raise_str(VALUE str
, int options
, const char *err
)
591 rb_exc_raise(rb_reg_error_desc(str
, options
, err
));
597 * rxp.casefold? => true or false
599 * Returns the value of the case-insensitive flag.
601 * /a/.casefold? #=> false
602 * /a/i.casefold? #=> true
603 * /(?i:a)/.casefold? #=> false
607 rb_reg_casefold_p(VALUE re
)
610 if (RREGEXP(re
)->ptr
->options
& ONIG_OPTION_IGNORECASE
) return Qtrue
;
617 * rxp.options => fixnum
619 * Returns the set of bits corresponding to the options used when creating this
620 * Regexp (see <code>Regexp::new</code> for details. Note that additional bits
621 * may be set in the returned options: these are used internally by the regular
622 * expression code. These extra bits are ignored if the options are passed to
623 * <code>Regexp::new</code>.
625 * Regexp::IGNORECASE #=> 1
626 * Regexp::EXTENDED #=> 2
627 * Regexp::MULTILINE #=> 4
629 * /cat/.options #=> 0
630 * /cat/ix.options #=> 3
631 * Regexp.new('cat', true).options #=> 1
632 * /\xa1\xa2/e.options #=> 16
635 * Regexp.new(r.source, r.options) #=> /cat/ix
639 rb_reg_options_m(VALUE re
)
641 int options
= rb_reg_options(re
);
642 return INT2NUM(options
);
646 reg_names_iter(const OnigUChar
*name
, const OnigUChar
*name_end
,
647 int back_num
, int *back_refs
, OnigRegex regex
, void *arg
)
649 VALUE ary
= (VALUE
)arg
;
650 rb_ary_push(ary
, rb_str_new((const char *)name
, name_end
-name
));
656 * rxp.names => [name1, name2, ...]
658 * Returns a list of names of captures as an array of strings.
660 * /(?<foo>.)(?<bar>.)(?<baz>.)/.names
661 * #=> ["foo", "bar", "baz"]
663 * /(?<foo>.)(?<foo>.)/.names
671 rb_reg_names(VALUE re
)
673 VALUE ary
= rb_ary_new();
675 onig_foreach_name(RREGEXP(re
)->ptr
, reg_names_iter
, (void*)ary
);
680 reg_named_captures_iter(const OnigUChar
*name
, const OnigUChar
*name_end
,
681 int back_num
, int *back_refs
, OnigRegex regex
, void *arg
)
683 VALUE hash
= (VALUE
)arg
;
684 VALUE ary
= rb_ary_new2(back_num
);
687 for(i
= 0; i
< back_num
; i
++)
688 rb_ary_store(ary
, i
, INT2NUM(back_refs
[i
]));
690 rb_hash_aset(hash
, rb_str_new((const char*)name
, name_end
-name
),ary
);
697 * rxp.named_captures => hash
699 * Returns a hash representing information about named captures of <i>rxp</i>.
701 * A key of the hash is a name of the named captures.
702 * A value of the hash is an array which is list of indexes of corresponding
705 * /(?<foo>.)(?<bar>.)/.named_captures
706 * #=> {"foo"=>[1], "bar"=>[2]}
708 * /(?<foo>.)(?<foo>.)/.named_captures
709 * #=> {"foo"=>[1, 2]}
711 * If there are no named captures, an empty hash is returned.
713 * /(.)(.)/.named_captures
718 rb_reg_named_captures(VALUE re
)
720 VALUE hash
= rb_hash_new();
722 onig_foreach_name(RREGEXP(re
)->ptr
, reg_named_captures_iter
, (void*)hash
);
727 make_regexp(const char *s
, long len
, rb_encoding
*enc
, int flags
, onig_errmsg_buffer err
)
733 /* Handle escaped characters first. */
735 /* Build a copy of the string (in dest) with the
736 escaped characters translated, and generate the regex
740 r
= onig_alloc_init(&rp
, flags
, ONIGENC_CASE_FOLD_DEFAULT
,
741 enc
, OnigDefaultSyntax
);
743 onig_error_code_to_str((UChar
*)err
, r
);
747 r
= onig_compile(rp
, (UChar
*)s
, (UChar
*)(s
+ len
), &einfo
);
751 (void )onig_error_code_to_str((UChar
*)err
, r
, &einfo
);
759 * Document-class: MatchData
761 * <code>MatchData</code> is the type of the special variable <code>$~</code>,
762 * and is the type of the object returned by <code>Regexp#match</code> and
763 * <code>Regexp.last_match</code>. It encapsulates all the results of a pattern
764 * match, results normally accessed through the special variables
765 * <code>$&</code>, <code>$'</code>, <code>$`</code>, <code>$1</code>,
766 * <code>$2</code>, and so on.
773 match_alloc(VALUE klass
)
775 NEWOBJ(match
, struct RMatch
);
776 OBJSETUP(match
, klass
, T_MATCH
);
781 match
->rmatch
= ALLOC(struct rmatch
);
782 MEMZERO(match
->rmatch
, struct rmatch
, 1);
793 pair_byte_cmp(const void *pair1
, const void *pair2
)
795 return ((pair_t
*)pair1
)->byte_pos
- ((pair_t
*)pair2
)->byte_pos
;
799 update_char_offset(VALUE match
)
801 struct rmatch
*rm
= RMATCH(match
)->rmatch
;
802 struct re_registers
*regs
;
809 if (rm
->char_offset_updated
)
813 num_regs
= rm
->regs
.num_regs
;
815 if (rm
->char_offset_num_allocated
< num_regs
) {
816 REALLOC_N(rm
->char_offset
, struct rmatch_offset
, num_regs
);
817 rm
->char_offset_num_allocated
= num_regs
;
820 enc
= rb_enc_get(RMATCH(match
)->str
);
821 if (rb_enc_mbmaxlen(enc
) == 1) {
822 for (i
= 0; i
< num_regs
; i
++) {
823 rm
->char_offset
[i
].beg
= BEG(i
);
824 rm
->char_offset
[i
].end
= END(i
);
826 rm
->char_offset_updated
= 1;
830 pairs
= ALLOCA_N(pair_t
, num_regs
*2);
832 for (i
= 0; i
< num_regs
; i
++) {
835 pairs
[num_pos
++].byte_pos
= BEG(i
);
836 pairs
[num_pos
++].byte_pos
= END(i
);
838 qsort(pairs
, num_pos
, sizeof(pair_t
), pair_byte_cmp
);
840 s
= p
= RSTRING_PTR(RMATCH(match
)->str
);
841 e
= s
+ RSTRING_LEN(RMATCH(match
)->str
);
843 for (i
= 0; i
< num_pos
; i
++) {
844 q
= s
+ pairs
[i
].byte_pos
;
845 c
+= rb_enc_strlen(p
, q
, enc
);
846 pairs
[i
].char_pos
= c
;
850 for (i
= 0; i
< num_regs
; i
++) {
853 rm
->char_offset
[i
].beg
= -1;
854 rm
->char_offset
[i
].end
= -1;
858 key
.byte_pos
= BEG(i
);
859 found
= bsearch(&key
, pairs
, num_pos
, sizeof(pair_t
), pair_byte_cmp
);
860 rm
->char_offset
[i
].beg
= found
->char_pos
;
862 key
.byte_pos
= END(i
);
863 found
= bsearch(&key
, pairs
, num_pos
, sizeof(pair_t
), pair_byte_cmp
);
864 rm
->char_offset
[i
].end
= found
->char_pos
;
867 rm
->char_offset_updated
= 1;
871 match_check(VALUE match
)
873 if (!RMATCH(match
)->regexp
) {
874 rb_raise(rb_eTypeError
, "uninitialized Match");
880 match_init_copy(VALUE obj
, VALUE orig
)
884 if (obj
== orig
) return obj
;
886 if (!rb_obj_is_instance_of(orig
, rb_obj_class(obj
))) {
887 rb_raise(rb_eTypeError
, "wrong argument class");
889 RMATCH(obj
)->str
= RMATCH(orig
)->str
;
890 RMATCH(obj
)->regexp
= RMATCH(orig
)->regexp
;
892 rm
= RMATCH(obj
)->rmatch
;
893 onig_region_copy(&rm
->regs
, RMATCH_REGS(orig
));
895 if (!RMATCH(orig
)->rmatch
->char_offset_updated
) {
896 rm
->char_offset_updated
= 0;
899 if (rm
->char_offset_num_allocated
< rm
->regs
.num_regs
) {
900 REALLOC_N(rm
->char_offset
, struct rmatch_offset
, rm
->regs
.num_regs
);
901 rm
->char_offset_num_allocated
= rm
->regs
.num_regs
;
903 MEMCPY(rm
->char_offset
, RMATCH(orig
)->rmatch
->char_offset
,
904 struct rmatch_offset
, rm
->regs
.num_regs
);
905 rm
->char_offset_updated
= 1;
914 * mtch.regexp => regexp
916 * Returns the regexp.
918 * m = /a.*b/.match("abc")
919 * m.regexp #=> /a.*b/
923 match_regexp(VALUE match
)
926 return RMATCH(match
)->regexp
;
931 * mtch.names => [name1, name2, ...]
933 * Returns a list of names of captures as an array of strings.
934 * It is same as mtch.regexp.names.
936 * /(?<foo>.)(?<bar>.)(?<baz>.)/.match("hoge").names
937 * #=> ["foo", "bar", "baz"]
939 * m = /(?<x>.)(?<y>.)?/.match("a") #=> #<MatchData "a" x:"a" y:nil>
940 * m.names #=> ["x", "y"]
944 match_names(VALUE match
)
947 return rb_reg_names(RMATCH(match
)->regexp
);
952 * mtch.length => integer
953 * mtch.size => integer
955 * Returns the number of elements in the match array.
957 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
963 match_size(VALUE match
)
966 return INT2FIX(RMATCH_REGS(match
)->num_regs
);
970 match_backref_number(VALUE match
, VALUE backref
)
975 struct re_registers
*regs
= RMATCH_REGS(match
);
976 VALUE regexp
= RMATCH(match
)->regexp
;
979 switch(TYPE(backref
)) {
981 return NUM2INT(backref
);
984 name
= rb_id2name(SYM2ID(backref
));
988 name
= StringValueCStr(backref
);
992 num
= onig_name_to_backref_number(RREGEXP(regexp
)->ptr
,
993 (const unsigned char*)name
,
994 (const unsigned char*)name
+ strlen(name
),
998 rb_raise(rb_eIndexError
, "undefined group name reference: %s", name
);
1007 * mtch.offset(n) => array
1009 * Returns a two-element array containing the beginning and ending offsets of
1010 * the <em>n</em>th match.
1011 * <em>n</em> can be a string or symbol to reference a named capture.
1013 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1014 * m.offset(0) #=> [1, 7]
1015 * m.offset(4) #=> [6, 7]
1017 * m = /(?<foo>.)(.)(?<bar>.)/.match("hoge")
1018 * p m.offset(:foo) #=> [0, 1]
1019 * p m.offset(:bar) #=> [2, 3]
1024 match_offset(VALUE match
, VALUE n
)
1026 int i
= match_backref_number(match
, n
);
1027 struct re_registers
*regs
= RMATCH_REGS(match
);
1030 if (i
< 0 || regs
->num_regs
<= i
)
1031 rb_raise(rb_eIndexError
, "index %d out of matches", i
);
1034 return rb_assoc_new(Qnil
, Qnil
);
1036 update_char_offset(match
);
1037 return rb_assoc_new(INT2FIX(RMATCH(match
)->rmatch
->char_offset
[i
].beg
),
1038 INT2FIX(RMATCH(match
)->rmatch
->char_offset
[i
].end
));
1044 * mtch.begin(n) => integer
1046 * Returns the offset of the start of the <em>n</em>th element of the match
1047 * array in the string.
1048 * <em>n</em> can be a string or symbol to reference a named capture.
1050 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1054 * m = /(?<foo>.)(.)(?<bar>.)/.match("hoge")
1055 * p m.begin(:foo) #=> 0
1056 * p m.begin(:bar) #=> 2
1060 match_begin(VALUE match
, VALUE n
)
1062 int i
= match_backref_number(match
, n
);
1063 struct re_registers
*regs
= RMATCH_REGS(match
);
1066 if (i
< 0 || regs
->num_regs
<= i
)
1067 rb_raise(rb_eIndexError
, "index %d out of matches", i
);
1072 update_char_offset(match
);
1073 return INT2FIX(RMATCH(match
)->rmatch
->char_offset
[i
].beg
);
1079 * mtch.end(n) => integer
1081 * Returns the offset of the character immediately following the end of the
1082 * <em>n</em>th element of the match array in the string.
1083 * <em>n</em> can be a string or symbol to reference a named capture.
1085 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1089 * m = /(?<foo>.)(.)(?<bar>.)/.match("hoge")
1090 * p m.end(:foo) #=> 1
1091 * p m.end(:bar) #=> 3
1095 match_end(VALUE match
, VALUE n
)
1097 int i
= match_backref_number(match
, n
);
1098 struct re_registers
*regs
= RMATCH_REGS(match
);
1101 if (i
< 0 || regs
->num_regs
<= i
)
1102 rb_raise(rb_eIndexError
, "index %d out of matches", i
);
1107 update_char_offset(match
);
1108 return INT2FIX(RMATCH(match
)->rmatch
->char_offset
[i
].end
);
1111 #define MATCH_BUSY FL_USER2
1114 rb_match_busy(VALUE match
)
1116 FL_SET(match
, MATCH_BUSY
);
1121 * rxp.fixed_encoding? => true or false
1123 * Returns false if rxp is applicable to
1124 * a string with any ASCII compatible encoding.
1125 * Returns true otherwise.
1128 * r.fixed_encoding? #=> false
1129 * r =~ "\u{6666} a" #=> 2
1130 * r =~ "\xa1\xa2 a".force_encoding("euc-jp") #=> 2
1131 * r =~ "abc".force_encoding("euc-jp") #=> 0
1134 * r.fixed_encoding? #=> true
1135 * r.encoding #=> #<Encoding:UTF-8>
1136 * r =~ "\u{6666} a" #=> 2
1137 * r =~ "\xa1\xa2".force_encoding("euc-jp") #=> ArgumentError
1138 * r =~ "abc".force_encoding("euc-jp") #=> 0
1141 * r.fixed_encoding? #=> true
1142 * r.encoding #=> #<Encoding:UTF-8>
1143 * r =~ "\u{6666} a" #=> 0
1144 * r =~ "\xa1\xa2".force_encoding("euc-jp") #=> ArgumentError
1145 * r =~ "abc".force_encoding("euc-jp") #=> nil
1149 rb_reg_fixed_encoding_p(VALUE re
)
1151 if (FL_TEST(re
, KCODE_FIXED
))
1158 rb_reg_preprocess(const char *p
, const char *end
, rb_encoding
*enc
,
1159 rb_encoding
**fixed_enc
, onig_errmsg_buffer err
);
1163 reg_enc_error(VALUE re
, VALUE str
)
1165 rb_raise(rb_eArgError
,
1166 "incompatible encoding regexp match (%s regexp with %s string)",
1167 rb_enc_name(RREGEXP(re
)->ptr
->enc
),
1168 rb_enc_name(rb_enc_get(str
)));
1172 rb_reg_prepare_enc(VALUE re
, VALUE str
, int warn
)
1174 rb_encoding
*enc
= 0;
1176 if (rb_enc_str_coderange(str
) == ENC_CODERANGE_BROKEN
) {
1177 rb_raise(rb_eArgError
,
1179 rb_enc_name(rb_enc_get(str
)));
1183 enc
= rb_enc_get(str
);
1184 if (!rb_enc_str_asciicompat_p(str
)) {
1185 if (RREGEXP(re
)->ptr
->enc
!= enc
) {
1186 reg_enc_error(re
, str
);
1189 else if (rb_reg_fixed_encoding_p(re
)) {
1190 if (RREGEXP(re
)->ptr
->enc
!= enc
&&
1191 (!rb_enc_asciicompat(RREGEXP(re
)->ptr
->enc
) ||
1192 rb_enc_str_coderange(str
) != ENC_CODERANGE_7BIT
)) {
1193 reg_enc_error(re
, str
);
1195 enc
= RREGEXP(re
)->ptr
->enc
;
1197 if (warn
&& (RBASIC(re
)->flags
& REG_ENCODING_NONE
) &&
1198 enc
!= rb_ascii8bit_encoding() &&
1199 rb_enc_str_coderange(str
) != ENC_CODERANGE_7BIT
) {
1200 rb_warn("regexp match /.../n against to %s string",
1207 rb_reg_prepare_re(VALUE re
, VALUE str
)
1209 regex_t
*reg
= RREGEXP(re
)->ptr
;
1210 onig_errmsg_buffer err
= "";
1212 OnigErrorInfo einfo
;
1213 const char *pattern
;
1215 rb_encoding
*fixed_enc
= 0;
1216 rb_encoding
*enc
= rb_reg_prepare_enc(re
, str
, 1);
1218 if (reg
->enc
== enc
) return reg
;
1221 reg
= RREGEXP(re
)->ptr
;
1222 pattern
= RREGEXP_SRC_PTR(re
);
1224 unescaped
= rb_reg_preprocess(
1225 pattern
, pattern
+ RREGEXP_SRC_LEN(re
), enc
,
1228 if (unescaped
== Qnil
) {
1229 rb_raise(rb_eArgError
, "regexp preprocess failed: %s", err
);
1232 r
= onig_new(®
, (UChar
* )RSTRING_PTR(unescaped
),
1233 (UChar
* )(RSTRING_PTR(unescaped
) + RSTRING_LEN(unescaped
)),
1235 OnigDefaultSyntax
, &einfo
);
1237 onig_error_code_to_str((UChar
*)err
, r
, &einfo
);
1238 rb_reg_raise(pattern
, RREGEXP_SRC_LEN(re
), err
, re
);
1241 RB_GC_GUARD(unescaped
);
1246 rb_reg_adjust_startpos(VALUE re
, VALUE str
, int pos
, int reverse
)
1252 enc
= rb_reg_prepare_enc(re
, str
, 0);
1258 range
= RSTRING_LEN(str
) - pos
;
1261 if (pos
> 0 && ONIGENC_MBC_MAXLEN(enc
) != 1 && pos
< RSTRING_LEN(str
)) {
1262 string
= (UChar
*)RSTRING_PTR(str
);
1265 p
= onigenc_get_right_adjust_char_head(enc
, string
, string
+ pos
);
1268 p
= ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc
, string
, string
+ pos
);
1277 rb_reg_search(VALUE re
, VALUE str
, int pos
, int reverse
)
1281 struct re_registers regi
, *regs
= ®i
;
1282 char *range
= RSTRING_PTR(str
);
1286 if (pos
> RSTRING_LEN(str
) || pos
< 0) {
1287 rb_backref_set(Qnil
);
1291 reg
= rb_reg_prepare_re(re
, str
);
1292 tmpreg
= reg
!= RREGEXP(re
)->ptr
;
1293 if (!tmpreg
) RREGEXP(re
)->usecnt
++;
1295 match
= rb_backref_get();
1296 if (!NIL_P(match
)) {
1297 if (FL_TEST(match
, MATCH_BUSY
)) {
1301 regs
= RMATCH_REGS(match
);
1305 MEMZERO(regs
, struct re_registers
, 1);
1308 range
+= RSTRING_LEN(str
);
1310 result
= onig_search(reg
,
1311 (UChar
*)(RSTRING_PTR(str
)),
1312 ((UChar
*)(RSTRING_PTR(str
)) + RSTRING_LEN(str
)),
1313 ((UChar
*)(RSTRING_PTR(str
)) + pos
),
1315 regs
, ONIG_OPTION_NONE
);
1316 if (!tmpreg
) RREGEXP(re
)->usecnt
--;
1318 if (RREGEXP(re
)->usecnt
) {
1322 onig_free(RREGEXP(re
)->ptr
);
1323 RREGEXP(re
)->ptr
= reg
;
1328 onig_region_free(regs
, 0);
1329 if (result
== ONIG_MISMATCH
) {
1330 rb_backref_set(Qnil
);
1334 onig_errmsg_buffer err
= "";
1335 onig_error_code_to_str((UChar
*)err
, result
);
1336 rb_reg_raise(RREGEXP_SRC_PTR(re
), RREGEXP_SRC_LEN(re
), err
, 0);
1341 match
= match_alloc(rb_cMatch
);
1342 onig_region_copy(RMATCH_REGS(match
), regs
);
1343 onig_region_free(regs
, 0);
1346 if (rb_safe_level() >= 3)
1349 FL_UNSET(match
, FL_TAINT
);
1352 RMATCH(match
)->str
= rb_str_new4(str
);
1353 RMATCH(match
)->regexp
= re
;
1354 RMATCH(match
)->rmatch
->char_offset_updated
= 0;
1355 rb_backref_set(match
);
1357 OBJ_INFECT(match
, re
);
1358 OBJ_INFECT(match
, str
);
1364 rb_reg_nth_defined(int nth
, VALUE match
)
1366 struct re_registers
*regs
;
1367 if (NIL_P(match
)) return Qnil
;
1369 regs
= RMATCH_REGS(match
);
1370 if (nth
>= regs
->num_regs
) {
1374 nth
+= regs
->num_regs
;
1375 if (nth
<= 0) return Qnil
;
1377 if (BEG(nth
) == -1) return Qfalse
;
1382 rb_reg_nth_match(int nth
, VALUE match
)
1385 long start
, end
, len
;
1386 struct re_registers
*regs
;
1388 if (NIL_P(match
)) return Qnil
;
1390 regs
= RMATCH_REGS(match
);
1391 if (nth
>= regs
->num_regs
) {
1395 nth
+= regs
->num_regs
;
1396 if (nth
<= 0) return Qnil
;
1399 if (start
== -1) return Qnil
;
1402 str
= rb_str_subseq(RMATCH(match
)->str
, start
, len
);
1403 OBJ_INFECT(str
, match
);
1408 rb_reg_last_match(VALUE match
)
1410 return rb_reg_nth_match(0, match
);
1416 * mtch.pre_match => str
1418 * Returns the portion of the original string before the current match.
1419 * Equivalent to the special variable <code>$`</code>.
1421 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1422 * m.pre_match #=> "T"
1426 rb_reg_match_pre(VALUE match
)
1429 struct re_registers
*regs
;
1431 if (NIL_P(match
)) return Qnil
;
1433 regs
= RMATCH_REGS(match
);
1434 if (BEG(0) == -1) return Qnil
;
1435 str
= rb_str_subseq(RMATCH(match
)->str
, 0, BEG(0));
1436 if (OBJ_TAINTED(match
)) OBJ_TAINT(str
);
1443 * mtch.post_match => str
1445 * Returns the portion of the original string after the current match.
1446 * Equivalent to the special variable <code>$'</code>.
1448 * m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
1449 * m.post_match #=> ": The Movie"
1453 rb_reg_match_post(VALUE match
)
1457 struct re_registers
*regs
;
1459 if (NIL_P(match
)) return Qnil
;
1461 regs
= RMATCH_REGS(match
);
1462 if (BEG(0) == -1) return Qnil
;
1463 str
= RMATCH(match
)->str
;
1465 str
= rb_str_subseq(str
, pos
, RSTRING_LEN(str
) - pos
);
1466 if (OBJ_TAINTED(match
)) OBJ_TAINT(str
);
1471 rb_reg_match_last(VALUE match
)
1474 struct re_registers
*regs
;
1476 if (NIL_P(match
)) return Qnil
;
1478 regs
= RMATCH_REGS(match
);
1479 if (BEG(0) == -1) return Qnil
;
1481 for (i
=regs
->num_regs
-1; BEG(i
) == -1 && i
> 0; i
--)
1483 if (i
== 0) return Qnil
;
1484 return rb_reg_nth_match(i
, match
);
1488 last_match_getter(void)
1490 return rb_reg_last_match(rb_backref_get());
1494 prematch_getter(void)
1496 return rb_reg_match_pre(rb_backref_get());
1500 postmatch_getter(void)
1502 return rb_reg_match_post(rb_backref_get());
1506 last_paren_match_getter(void)
1508 return rb_reg_match_last(rb_backref_get());
1512 match_array(VALUE match
, int start
)
1514 struct re_registers
*regs
= RMATCH_REGS(match
);
1515 VALUE ary
= rb_ary_new2(regs
->num_regs
);
1516 VALUE target
= RMATCH(match
)->str
;
1518 int taint
= OBJ_TAINTED(match
);
1521 for (i
=start
; i
<regs
->num_regs
; i
++) {
1522 if (regs
->beg
[i
] == -1) {
1523 rb_ary_push(ary
, Qnil
);
1526 VALUE str
= rb_str_subseq(target
, regs
->beg
[i
], regs
->end
[i
]-regs
->beg
[i
]);
1527 if (taint
) OBJ_TAINT(str
);
1528 rb_ary_push(ary
, str
);
1535 /* [MG]:FIXME: I put parens around the /.../.match() in the first line of the
1536 second example to prevent the '*' followed by a '/' from ending the
1541 * mtch.to_a => anArray
1543 * Returns the array of matches.
1545 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1546 * m.to_a #=> ["HX1138", "H", "X", "113", "8"]
1548 * Because <code>to_a</code> is called when expanding
1549 * <code>*</code><em>variable</em>, there's a useful assignment
1550 * shortcut for extracting matched fields. This is slightly slower than
1551 * accessing the fields directly (as an intermediate array is
1554 * all,f1,f2,f3 = *(/(.)(.)(\d+)(\d)/.match("THX1138."))
1562 match_to_a(VALUE match
)
1564 return match_array(match
, 0);
1570 * mtch.captures => array
1572 * Returns the array of captures; equivalent to <code>mtch.to_a[1..-1]</code>.
1574 * f1,f2,f3,f4 = /(.)(.)(\d+)(\d)/.match("THX1138.").captures
1581 match_captures(VALUE match
)
1583 return match_array(match
, 1);
1587 name_to_backref_number(struct re_registers
*regs
, VALUE regexp
, const char* name
, const char* name_end
)
1591 num
= onig_name_to_backref_number(RREGEXP(regexp
)->ptr
,
1592 (const unsigned char* )name
, (const unsigned char* )name_end
, regs
);
1597 VALUE s
= rb_str_new(name
, (long )(name_end
- name
));
1598 rb_raise(rb_eIndexError
, "undefined group name reference: %s",
1605 * mtch[i] => str or nil
1606 * mtch[start, length] => array
1607 * mtch[range] => array
1608 * mtch[name] => str or nil
1610 * Match Reference---<code>MatchData</code> acts as an array, and may be
1611 * accessed using the normal array indexing techniques. <i>mtch</i>[0] is
1612 * equivalent to the special variable <code>$&</code>, and returns the entire
1613 * matched string. <i>mtch</i>[1], <i>mtch</i>[2], and so on return the values
1614 * of the matched backreferences (portions of the pattern between parentheses).
1616 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1617 * m #=> #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
1619 * m[1, 2] #=> ["H", "X"]
1620 * m[1..3] #=> ["H", "X", "113"]
1621 * m[-3, 2] #=> ["X", "113"]
1623 * m = /(?<foo>a+)b/.match("ccaaab")
1624 * m #=> #<MatchData "aaab" foo:"aaa">
1625 * m["foo"] #=> "aaa"
1630 match_aref(int argc
, VALUE
*argv
, VALUE match
)
1635 rb_scan_args(argc
, argv
, "11", &idx
, &rest
);
1638 if (FIXNUM_P(idx
)) {
1639 if (FIX2INT(idx
) >= 0) {
1640 return rb_reg_nth_match(FIX2INT(idx
), match
);
1647 switch (TYPE(idx
)) {
1649 p
= rb_id2name(SYM2ID(idx
));
1650 goto name_to_backref
;
1653 p
= StringValuePtr(idx
);
1656 num
= name_to_backref_number(RMATCH_REGS(match
),
1657 RMATCH(match
)->regexp
, p
, p
+ strlen(p
));
1658 return rb_reg_nth_match(num
, match
);
1667 return rb_ary_aref(argc
, argv
, match_to_a(match
));
1671 match_entry(VALUE match
, long n
)
1673 return rb_reg_nth_match(n
, match
);
1680 * mtch.values_at([index]*) => array
1682 * Uses each <i>index</i> to access the matching values, returning an array of
1683 * the corresponding matches.
1685 * m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
1686 * m.to_a #=> ["HX1138", "H", "X", "113", "8"]
1687 * m.values_at(0, 2, -2) #=> ["HX1138", "X", "113"]
1691 match_values_at(int argc
, VALUE
*argv
, VALUE match
)
1693 struct re_registers
*regs
= RMATCH_REGS(match
);
1695 return rb_get_values_at(match
, regs
->num_regs
, argc
, argv
, match_entry
);
1703 * Returns the entire matched string.
1705 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1706 * m.to_s #=> "HX1138"
1710 match_to_s(VALUE match
)
1712 VALUE str
= rb_reg_last_match(match
);
1715 if (NIL_P(str
)) str
= rb_str_new(0,0);
1716 if (OBJ_TAINTED(match
)) OBJ_TAINT(str
);
1717 if (OBJ_TAINTED(RMATCH(match
)->str
)) OBJ_TAINT(str
);
1724 * mtch.string => str
1726 * Returns a frozen copy of the string passed in to <code>match</code>.
1728 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1729 * m.string #=> "THX1138."
1733 match_string(VALUE match
)
1736 return RMATCH(match
)->str
; /* str is frozen */
1739 struct backref_name_tag
{
1745 match_inspect_name_iter(const OnigUChar
*name
, const OnigUChar
*name_end
,
1746 int back_num
, int *back_refs
, OnigRegex regex
, void *arg0
)
1748 struct backref_name_tag
*arg
= (struct backref_name_tag
*)arg0
;
1751 for (i
= 0; i
< back_num
; i
++) {
1752 arg
[back_refs
[i
]].name
= name
;
1753 arg
[back_refs
[i
]].len
= name_end
- name
;
1760 * mtch.inspect => str
1762 * Returns a printable version of <i>mtch</i>.
1764 * puts /.$/.match("foo").inspect
1765 * #=> #<MatchData "o">
1767 * puts /(.)(.)(.)/.match("foo").inspect
1768 * #=> #<MatchData "foo" 1:"f" 2:"o" 3:"o">
1770 * puts /(.)(.)?(.)/.match("fo").inspect
1771 * #=> #<MatchData "fo" 1:"f" 2:nil 3:"o">
1773 * puts /(?<foo>.)(?<bar>.)(?<baz>.)/.match("hoge").inspect
1774 * #=> #<MatchData "hog" foo:"h" bar:"o" baz:"g">
1779 match_inspect(VALUE match
)
1781 const char *cname
= rb_obj_classname(match
);
1784 struct re_registers
*regs
= RMATCH_REGS(match
);
1785 int num_regs
= regs
->num_regs
;
1786 struct backref_name_tag
*names
;
1787 VALUE regexp
= RMATCH(match
)->regexp
;
1790 return rb_sprintf("#<%s:%p>", cname
, (void*)match
);
1793 names
= ALLOCA_N(struct backref_name_tag
, num_regs
);
1794 MEMZERO(names
, struct backref_name_tag
, num_regs
);
1796 onig_foreach_name(RREGEXP(regexp
)->ptr
,
1797 match_inspect_name_iter
, names
);
1799 str
= rb_str_buf_new2("#<");
1800 rb_str_buf_cat2(str
, cname
);
1802 for (i
= 0; i
< num_regs
; i
++) {
1804 rb_str_buf_cat2(str
, " ");
1807 rb_str_buf_cat(str
, (const char *)names
[i
].name
, names
[i
].len
);
1809 rb_str_catf(str
, "%d", i
);
1811 rb_str_buf_cat2(str
, ":");
1813 v
= rb_reg_nth_match(i
, match
);
1815 rb_str_buf_cat2(str
, "nil");
1817 rb_str_buf_append(str
, rb_str_inspect(v
));
1819 rb_str_buf_cat2(str
, ">");
1827 read_escaped_byte(const char **pp
, const char *end
, onig_errmsg_buffer err
)
1829 const char *p
= *pp
;
1831 int meta_prefix
= 0, ctrl_prefix
= 0;
1836 if (p
== end
|| *p
++ != '\\') {
1837 strcpy(err
, "too short escaped multibyte character");
1843 strcpy(err
, "too short escape sequence");
1847 case '\\': code
= '\\'; break;
1848 case 'n': code
= '\n'; break;
1849 case 't': code
= '\t'; break;
1850 case 'r': code
= '\r'; break;
1851 case 'f': code
= '\f'; break;
1852 case 'v': code
= '\013'; break;
1853 case 'a': code
= '\007'; break;
1854 case 'e': code
= '\033'; break;
1857 case '0': case '1': case '2': case '3':
1858 case '4': case '5': case '6': case '7':
1860 code
= ruby_scan_oct(p
, end
< p
+3 ? end
-p
: 3, &len
);
1864 case 'x': /* \xHH */
1865 code
= ruby_scan_hex(p
, end
< p
+2 ? end
-p
: 2, &len
);
1867 strcpy(err
, "invalid hex escape");
1873 case 'M': /* \M-X, \M-\C-X, \M-\cX */
1875 strcpy(err
, "duplicate meta escape");
1879 if (p
+1 < end
&& *p
++ == '-' && (*p
& 0x80) == 0) {
1889 strcpy(err
, "too short meta escape");
1892 case 'C': /* \C-X, \C-\M-X */
1893 if (p
== end
|| *p
++ != '-') {
1894 strcpy(err
, "too short control escape");
1897 case 'c': /* \cX, \c\M-X */
1899 strcpy(err
, "duplicate control escape");
1903 if (p
< end
&& (*p
& 0x80) == 0) {
1913 strcpy(err
, "too short control escape");
1917 strcpy(err
, "unexpected escape sequence");
1920 if (code
< 0 || 0xff < code
) {
1921 strcpy(err
, "invalid escape code");
1935 unescape_escaped_nonascii(const char **pp
, const char *end
, rb_encoding
*enc
,
1936 VALUE buf
, rb_encoding
**encp
, onig_errmsg_buffer err
)
1938 const char *p
= *pp
;
1939 int chmaxlen
= rb_enc_mbmaxlen(enc
);
1940 char *chbuf
= ALLOCA_N(char, chmaxlen
);
1945 memset(chbuf
, 0, chmaxlen
);
1947 byte
= read_escaped_byte(&p
, end
, err
);
1952 chbuf
[chlen
++] = byte
;
1953 while (chlen
< chmaxlen
&&
1954 MBCLEN_NEEDMORE_P(rb_enc_precise_mbclen(chbuf
, chbuf
+chlen
, enc
))) {
1955 byte
= read_escaped_byte(&p
, end
, err
);
1959 chbuf
[chlen
++] = byte
;
1962 l
= rb_enc_precise_mbclen(chbuf
, chbuf
+chlen
, enc
);
1963 if (MBCLEN_INVALID_P(l
)) {
1964 strcpy(err
, "invalid multibyte escape");
1967 if (1 < chlen
|| (chbuf
[0] & 0x80)) {
1968 rb_str_buf_cat(buf
, chbuf
, chlen
);
1972 else if (*encp
!= enc
) {
1973 strcpy(err
, "escaped non ASCII character in UTF-8 regexp");
1979 snprintf(escbuf
, sizeof(escbuf
), "\\x%02X", chbuf
[0]&0xff);
1980 rb_str_buf_cat(buf
, escbuf
, 4);
1987 check_unicode_range(unsigned long code
, onig_errmsg_buffer err
)
1989 if ((0xd800 <= code
&& code
<= 0xdfff) || /* Surrogates */
1991 strcpy(err
, "invalid Unicode range");
1998 append_utf8(unsigned long uv
,
1999 VALUE buf
, rb_encoding
**encp
, onig_errmsg_buffer err
)
2001 if (check_unicode_range(uv
, err
) != 0)
2005 snprintf(escbuf
, sizeof(escbuf
), "\\x%02X", (int)uv
);
2006 rb_str_buf_cat(buf
, escbuf
, 4);
2011 len
= rb_uv_to_utf8(utf8buf
, uv
);
2012 rb_str_buf_cat(buf
, utf8buf
, len
);
2015 *encp
= rb_utf8_encoding();
2016 else if (*encp
!= rb_utf8_encoding()) {
2017 strcpy(err
, "UTF-8 character in non UTF-8 regexp");
2025 unescape_unicode_list(const char **pp
, const char *end
,
2026 VALUE buf
, rb_encoding
**encp
, onig_errmsg_buffer err
)
2028 const char *p
= *pp
;
2029 int has_unicode
= 0;
2033 while (p
< end
&& ISSPACE(*p
)) p
++;
2036 code
= ruby_scan_hex(p
, end
-p
, &len
);
2039 if (6 < len
) { /* max 10FFFF */
2040 strcpy(err
, "invalid Unicode range");
2044 if (append_utf8(code
, buf
, encp
, err
) != 0)
2048 while (p
< end
&& ISSPACE(*p
)) p
++;
2051 if (has_unicode
== 0) {
2052 strcpy(err
, "invalid Unicode list");
2062 unescape_unicode_bmp(const char **pp
, const char *end
,
2063 VALUE buf
, rb_encoding
**encp
, onig_errmsg_buffer err
)
2065 const char *p
= *pp
;
2070 strcpy(err
, "invalid Unicode escape");
2073 code
= ruby_scan_hex(p
, 4, &len
);
2075 strcpy(err
, "invalid Unicode escape");
2078 if (append_utf8(code
, buf
, encp
, err
) != 0)
2085 unescape_nonascii(const char *p
, const char *end
, rb_encoding
*enc
,
2086 VALUE buf
, rb_encoding
**encp
, int *has_property
,
2087 onig_errmsg_buffer err
)
2093 int chlen
= rb_enc_precise_mbclen(p
, end
, enc
);
2094 if (!MBCLEN_CHARFOUND_P(chlen
)) {
2095 strcpy(err
, "invalid multibyte character");
2098 chlen
= MBCLEN_CHARFOUND_LEN(chlen
);
2099 if (1 < chlen
|| (*p
& 0x80)) {
2100 rb_str_buf_cat(buf
, p
, chlen
);
2104 else if (*encp
!= enc
) {
2105 strcpy(err
, "non ASCII character in UTF-8 regexp");
2114 strcpy(err
, "too short escape sequence");
2118 case '1': case '2': case '3':
2119 case '4': case '5': case '6': case '7': /* \O, \OO, \OOO or backref */
2122 if (ruby_scan_oct(p
-1, end
-(p
-1), &octlen
) <= 0177) {
2123 /* backref or 7bit octal.
2124 no need to unescape anyway.
2125 re-escaping may break backref */
2129 /* xxx: How about more than 199 subexpressions? */
2131 case '0': /* \0, \0O, \0OO */
2133 case 'x': /* \xHH */
2134 case 'c': /* \cX, \c\M-X */
2135 case 'C': /* \C-X, \C-\M-X */
2136 case 'M': /* \M-X, \M-\C-X, \M-\cX */
2138 if (unescape_escaped_nonascii(&p
, end
, enc
, buf
, encp
, err
) != 0)
2144 strcpy(err
, "too short escape sequence");
2148 /* \u{H HH HHH HHHH HHHHH HHHHHH ...} */
2150 if (unescape_unicode_list(&p
, end
, buf
, encp
, err
) != 0)
2152 if (p
== end
|| *p
++ != '}') {
2153 strcpy(err
, "invalid Unicode list");
2160 if (unescape_unicode_bmp(&p
, end
, buf
, encp
, err
) != 0)
2165 case 'p': /* \p{Hiragana} */
2171 default: /* \n, \\, \d, \9, etc. */
2175 rb_str_buf_cat(buf
, smallbuf
, 2);
2181 rb_str_buf_cat(buf
, &c
, 1);
2190 rb_reg_preprocess(const char *p
, const char *end
, rb_encoding
*enc
,
2191 rb_encoding
**fixed_enc
, onig_errmsg_buffer err
)
2194 int has_property
= 0;
2196 buf
= rb_str_buf_new(0);
2198 if (rb_enc_asciicompat(enc
))
2202 rb_enc_associate(buf
, enc
);
2205 if (unescape_nonascii(p
, end
, enc
, buf
, fixed_enc
, &has_property
, err
) != 0)
2208 if (has_property
&& !*fixed_enc
) {
2213 rb_enc_associate(buf
, *fixed_enc
);
2220 rb_reg_check_preprocess(VALUE str
)
2222 rb_encoding
*fixed_enc
= 0;
2223 onig_errmsg_buffer err
= "";
2229 p
= RSTRING_PTR(str
);
2230 end
= p
+ RSTRING_LEN(str
);
2231 enc
= rb_enc_get(str
);
2233 buf
= rb_reg_preprocess(p
, end
, enc
, &fixed_enc
, err
);
2237 return rb_reg_error_desc(str
, 0, err
);
2243 rb_reg_preprocess_dregexp(VALUE ary
)
2245 rb_encoding
*fixed_enc
= 0;
2246 rb_encoding
*regexp_enc
= 0;
2247 onig_errmsg_buffer err
= "";
2250 int argc
= RARRAY_LEN(ary
);
2251 VALUE
*argv
= RARRAY_PTR(ary
);
2254 rb_raise(rb_eArgError
, "no arguments given");
2257 for (i
= 0; i
< argc
; i
++) {
2258 VALUE str
= argv
[i
];
2261 rb_encoding
*src_enc
;
2264 p
= RSTRING_PTR(str
);
2265 end
= p
+ RSTRING_LEN(str
);
2266 src_enc
= rb_enc_get(str
);
2268 buf
= rb_reg_preprocess(p
, end
, src_enc
, &fixed_enc
, err
);
2271 rb_raise(rb_eArgError
, "%s", err
);
2273 if (fixed_enc
!= 0) {
2274 if (regexp_enc
!= 0 && regexp_enc
!= fixed_enc
) {
2275 rb_raise(rb_eArgError
, "encoding mismatch in dynamic regexp : %s and %s",
2276 rb_enc_name(regexp_enc
), rb_enc_name(fixed_enc
));
2278 regexp_enc
= fixed_enc
;
2282 result
= rb_str_new3(str
);
2284 rb_str_buf_append(result
, str
);
2287 rb_enc_associate(result
, regexp_enc
);
2294 rb_reg_initialize(VALUE obj
, const char *s
, int len
, rb_encoding
*enc
,
2295 int options
, onig_errmsg_buffer err
)
2297 struct RRegexp
*re
= RREGEXP(obj
);
2299 rb_encoding
*fixed_enc
= 0;
2300 rb_encoding
*a_enc
= rb_ascii8bit_encoding();
2302 if (!OBJ_UNTRUSTED(obj
) && rb_safe_level() >= 4)
2303 rb_raise(rb_eSecurityError
, "Insecure: can't modify regexp");
2304 rb_check_frozen(obj
);
2305 if (FL_TEST(obj
, REG_LITERAL
))
2306 rb_raise(rb_eSecurityError
, "can't modify literal regexp");
2308 rb_raise(rb_eTypeError
, "already initialized regexp");
2311 unescaped
= rb_reg_preprocess(s
, s
+len
, enc
, &fixed_enc
, err
);
2312 if (unescaped
== Qnil
)
2316 if ((fixed_enc
!= enc
&& (options
& ARG_ENCODING_FIXED
)) ||
2317 (fixed_enc
!= a_enc
&& (options
& ARG_ENCODING_NONE
))) {
2318 strcpy(err
, "incompatible character encoding");
2321 if (fixed_enc
!= a_enc
) {
2322 options
|= ARG_ENCODING_FIXED
;
2326 else if (!(options
& ARG_ENCODING_FIXED
)) {
2327 enc
= rb_usascii_encoding();
2330 rb_enc_associate((VALUE
)re
, enc
);
2331 if ((options
& ARG_ENCODING_FIXED
) || fixed_enc
) {
2332 re
->basic
.flags
|= KCODE_FIXED
;
2334 if (options
& ARG_ENCODING_NONE
) {
2335 re
->basic
.flags
|= REG_ENCODING_NONE
;
2338 re
->ptr
= make_regexp(RSTRING_PTR(unescaped
), RSTRING_LEN(unescaped
), enc
,
2339 options
& ARG_REG_OPTION_MASK
, err
);
2340 if (!re
->ptr
) return -1;
2341 re
->src
= rb_enc_str_new(s
, len
, enc
);
2342 OBJ_FREEZE(re
->src
);
2343 RB_GC_GUARD(unescaped
);
2348 rb_reg_initialize_str(VALUE obj
, VALUE str
, int options
, onig_errmsg_buffer err
)
2351 rb_encoding
*enc
= rb_enc_get(str
);
2352 if (options
& ARG_ENCODING_NONE
) {
2353 rb_encoding
*ascii8bit
= rb_ascii8bit_encoding();
2354 if (enc
!= ascii8bit
) {
2355 if (rb_enc_str_coderange(str
) != ENC_CODERANGE_7BIT
) {
2356 strcpy(err
, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
2362 ret
= rb_reg_initialize(obj
, RSTRING_PTR(str
), RSTRING_LEN(str
), enc
,
2369 rb_reg_s_alloc(VALUE klass
)
2371 NEWOBJ(re
, struct RRegexp
);
2372 OBJSETUP(re
, klass
, T_REGEXP
);
2382 rb_reg_new_str(VALUE s
, int options
)
2384 VALUE re
= rb_reg_s_alloc(rb_cRegexp
);
2385 onig_errmsg_buffer err
= "";
2387 if (rb_reg_initialize_str(re
, s
, options
, err
) != 0) {
2388 rb_reg_raise_str(s
, options
, err
);
2395 rb_reg_new_ary(VALUE ary
, int opt
)
2397 return rb_reg_new_str(rb_reg_preprocess_dregexp(ary
), opt
);
2401 rb_enc_reg_new(const char *s
, long len
, rb_encoding
*enc
, int options
)
2403 VALUE re
= rb_reg_s_alloc(rb_cRegexp
);
2404 onig_errmsg_buffer err
= "";
2406 if (rb_reg_initialize(re
, s
, len
, enc
, options
, err
) != 0) {
2407 rb_enc_reg_raise(s
, len
, enc
, options
, err
);
2414 rb_reg_new(const char *s
, long len
, int options
)
2416 return rb_enc_reg_new(s
, len
, rb_ascii8bit_encoding(), options
);
2420 rb_reg_compile(VALUE str
, int options
)
2422 VALUE re
= rb_reg_s_alloc(rb_cRegexp
);
2423 onig_errmsg_buffer err
= "";
2425 if (!str
) str
= rb_str_new(0,0);
2426 if (rb_reg_initialize_str(re
, str
, options
, err
) != 0) {
2427 rb_set_errinfo(rb_reg_error_desc(str
, options
, err
));
2430 FL_SET(re
, REG_LITERAL
);
2434 static VALUE reg_cache
;
2437 rb_reg_regcomp(VALUE str
)
2439 volatile VALUE save_str
= str
;
2440 if (reg_cache
&& RREGEXP_SRC_LEN(reg_cache
) == RSTRING_LEN(str
)
2441 && ENCODING_GET(reg_cache
) == ENCODING_GET(str
)
2442 && memcmp(RREGEXP_SRC_PTR(reg_cache
), RSTRING_PTR(str
), RSTRING_LEN(str
)) == 0)
2445 return reg_cache
= rb_reg_new_str(save_str
, 0);
2450 * rxp.hash => fixnum
2452 * Produce a hash based on the text and options of this regular expression.
2456 rb_reg_hash(VALUE re
)
2462 hashval
= RREGEXP(re
)->ptr
->options
;
2463 len
= RREGEXP_SRC_LEN(re
);
2464 p
= RREGEXP_SRC_PTR(re
);
2466 hashval
= hashval
* 33 + *p
++;
2468 hashval
= hashval
+ (hashval
>>5);
2470 return INT2FIX(hashval
);
2476 * rxp == other_rxp => true or false
2477 * rxp.eql?(other_rxp) => true or false
2479 * Equality---Two regexps are equal if their patterns are identical, they have
2480 * the same character set code, and their <code>casefold?</code> values are the
2483 * /abc/ == /abc/x #=> false
2484 * /abc/ == /abc/i #=> false
2485 * /abc/ == /abc/n #=> false
2486 * /abc/u == /abc/n #=> false
2490 rb_reg_equal(VALUE re1
, VALUE re2
)
2492 if (re1
== re2
) return Qtrue
;
2493 if (TYPE(re2
) != T_REGEXP
) return Qfalse
;
2494 rb_reg_check(re1
); rb_reg_check(re2
);
2495 if (FL_TEST(re1
, KCODE_FIXED
) != FL_TEST(re2
, KCODE_FIXED
)) return Qfalse
;
2496 if (RREGEXP(re1
)->ptr
->options
!= RREGEXP(re2
)->ptr
->options
) return Qfalse
;
2497 if (RREGEXP_SRC_LEN(re1
) != RREGEXP_SRC_LEN(re2
)) return Qfalse
;
2498 if (ENCODING_GET(re1
) != ENCODING_GET(re2
)) return Qfalse
;
2499 if (memcmp(RREGEXP_SRC_PTR(re1
), RREGEXP_SRC_PTR(re2
), RREGEXP_SRC_LEN(re1
)) == 0) {
2506 reg_operand(VALUE s
, int check
)
2509 return rb_sym_to_s(s
);
2512 VALUE tmp
= rb_check_string_type(s
);
2513 if (check
&& NIL_P(tmp
)) {
2514 rb_raise(rb_eTypeError
, "can't convert %s to String",
2515 rb_obj_classname(s
));
2522 reg_match_pos(VALUE re
, VALUE
*strp
, long pos
)
2527 rb_backref_set(Qnil
);
2530 *strp
= str
= reg_operand(str
, Qtrue
);
2533 VALUE l
= rb_str_length(str
);
2539 pos
= rb_reg_adjust_startpos(re
, str
, pos
, 0);
2541 return rb_reg_search(re
, str
, pos
, 0);
2546 * rxp =~ str => integer or nil
2548 * Match---Matches <i>rxp</i> against <i>str</i>.
2550 * /at/ =~ "input data" #=> 7
2551 * /ax/ =~ "input data" #=> nil
2553 * If <code>=~</code> is used with a regexp literal with named captures,
2554 * captured strings (or nil) is assigned to local variables named by
2555 * the capture names.
2557 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ " x = y "
2561 * If it is not matched, nil is assigned for the variables.
2563 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ " x = "
2567 * This assignment is implemented in the Ruby parser.
2568 * So a regexp literal is required for the assignment.
2569 * The assignment is not occur if the regexp is not a literal.
2571 * re = /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/
2573 * p lhs # undefined local variable
2574 * p rhs # undefined local variable
2576 * A regexp interpolation, <code>#{}</code>, also disables
2579 * rhs_pat = /(?<rhs>\w+)/
2580 * /(?<lhs>\w+)\s*=\s*#{rhs_pat}/ =~ "x = y"
2581 * p lhs # undefined local variable
2586 rb_reg_match(VALUE re
, VALUE str
)
2588 long pos
= reg_match_pos(re
, &str
, 0);
2589 if (pos
< 0) return Qnil
;
2590 pos
= rb_str_sublen(str
, pos
);
2591 return LONG2FIX(pos
);
2596 * rxp === str => true or false
2598 * Case Equality---Synonym for <code>Regexp#=~</code> used in case statements.
2602 * when /^[a-z]*$/; print "Lower case\n"
2603 * when /^[A-Z]*$/; print "Upper case\n"
2604 * else; print "Mixed case\n"
2607 * <em>produces:</em>
2613 rb_reg_eqq(VALUE re
, VALUE str
)
2617 str
= reg_operand(str
, Qfalse
);
2619 rb_backref_set(Qnil
);
2622 start
= rb_reg_search(re
, str
, 0, 0);
2632 * ~ rxp => integer or nil
2634 * Match---Matches <i>rxp</i> against the contents of <code>$_</code>.
2635 * Equivalent to <code><i>rxp</i> =~ $_</code>.
2642 rb_reg_match2(VALUE re
)
2645 VALUE line
= rb_lastline_get();
2647 if (TYPE(line
) != T_STRING
) {
2648 rb_backref_set(Qnil
);
2652 start
= rb_reg_search(re
, line
, 0, 0);
2656 start
= rb_str_sublen(line
, start
);
2657 return LONG2FIX(start
);
2663 * rxp.match(str) => matchdata or nil
2664 * rxp.match(str,pos) => matchdata or nil
2666 * Returns a <code>MatchData</code> object describing the match, or
2667 * <code>nil</code> if there was no match. This is equivalent to retrieving the
2668 * value of the special variable <code>$~</code> following a normal match.
2669 * If the second parameter is present, it specifies the position in the string
2670 * to begin the search.
2672 * /(.)(.)(.)/.match("abc")[2] #=> "b"
2673 * /(.)(.)/.match("abc", 1)[2] #=> "c"
2675 * If a block is given, invoke the block with MatchData if match succeed, so
2676 * that you can write
2678 * pat.match(str) {|m| ...}
2682 * if m = pat.match(str)
2686 * The return value is a value from block execution in this case.
2690 rb_reg_match_m(int argc
, VALUE
*argv
, VALUE re
)
2692 VALUE result
, str
, initpos
;
2695 if (rb_scan_args(argc
, argv
, "11", &str
, &initpos
) == 2) {
2696 pos
= NUM2LONG(initpos
);
2702 pos
= reg_match_pos(re
, &str
, pos
);
2704 rb_backref_set(Qnil
);
2707 result
= rb_backref_get();
2708 rb_match_busy(result
);
2709 if (!NIL_P(result
) && rb_block_given_p()) {
2710 return rb_yield(result
);
2716 * Document-method: compile
2718 * Synonym for <code>Regexp.new</code>
2724 * Regexp.new(string [, options]) => regexp
2725 * Regexp.new(regexp) => regexp
2726 * Regexp.compile(string [, options]) => regexp
2727 * Regexp.compile(regexp) => regexp
2729 * Constructs a new regular expression from <i>pattern</i>, which can be either
2730 * a <code>String</code> or a <code>Regexp</code> (in which case that regexp's
2731 * options are propagated, and new options may not be specified (a change as of
2732 * Ruby 1.8). If <i>options</i> is a <code>Fixnum</code>, it should be one or
2733 * more of the constants <code>Regexp::EXTENDED</code>,
2734 * <code>Regexp::IGNORECASE</code>, and <code>Regexp::MULTILINE</code>,
2735 * <em>or</em>-ed together. Otherwise, if <i>options</i> is not
2736 * <code>nil</code>, the regexp will be case insensitive.
2738 * r1 = Regexp.new('^a-z+:\\s+\w+') #=> /^a-z+:\s+\w+/
2739 * r2 = Regexp.new('cat', true) #=> /cat/i
2740 * r3 = Regexp.new('dog', Regexp::EXTENDED) #=> /dog/x
2741 * r4 = Regexp.new(r2) #=> /cat/i
2745 rb_reg_initialize_m(int argc
, VALUE
*argv
, VALUE self
)
2747 onig_errmsg_buffer err
= "";
2754 if (argc
== 0 || argc
> 3) {
2755 rb_raise(rb_eArgError
, "wrong number of arguments");
2757 if (TYPE(argv
[0]) == T_REGEXP
) {
2761 rb_warn("flags ignored");
2764 flags
= rb_reg_options(re
);
2765 ptr
= RREGEXP_SRC_PTR(re
);
2766 len
= RREGEXP_SRC_LEN(re
);
2767 enc
= rb_enc_get(re
);
2768 if (rb_reg_initialize(self
, ptr
, len
, enc
, flags
, err
)) {
2769 str
= rb_enc_str_new(ptr
, len
, enc
);
2770 rb_reg_raise_str(str
, flags
, err
);
2775 if (FIXNUM_P(argv
[1])) flags
= FIX2INT(argv
[1]);
2776 else if (RTEST(argv
[1])) flags
= ONIG_OPTION_IGNORECASE
;
2779 if (argc
== 3 && !NIL_P(argv
[2])) {
2780 char *kcode
= StringValuePtr(argv
[2]);
2781 if (kcode
[0] == 'n' || kcode
[1] == 'N') {
2782 enc
= rb_ascii8bit_encoding();
2783 flags
|= ARG_ENCODING_FIXED
;
2786 rb_warning("encoding option is obsolete - %s", kcode
);
2790 ptr
= StringValuePtr(str
);
2792 ? rb_reg_initialize(self
, ptr
, RSTRING_LEN(str
), enc
, flags
, err
)
2793 : rb_reg_initialize_str(self
, str
, flags
, err
)) {
2794 rb_reg_raise_str(str
, flags
, err
);
2801 rb_reg_quote(VALUE str
)
2803 rb_encoding
*enc
= rb_enc_get(str
);
2807 int ascii_only
= rb_enc_str_asciionly_p(str
);
2809 s
= RSTRING_PTR(str
);
2810 send
= s
+ RSTRING_LEN(str
);
2812 c
= rb_enc_ascget(s
, send
, &clen
, enc
);
2814 s
+= mbclen(s
, send
, enc
);
2818 case '[': case ']': case '{': case '}':
2819 case '(': case ')': case '|': case '-':
2820 case '*': case '.': case '\\':
2821 case '?': case '+': case '^': case '$':
2823 case '\t': case '\f': case '\v': case '\n': case '\r':
2828 tmp
= rb_str_new3(str
);
2830 rb_enc_associate(tmp
, rb_usascii_encoding());
2835 tmp
= rb_str_new(0, RSTRING_LEN(str
)*2);
2837 rb_enc_associate(tmp
, rb_usascii_encoding());
2840 rb_enc_copy(tmp
, str
);
2842 t
= RSTRING_PTR(tmp
);
2843 /* copy upto metacharacter */
2844 memcpy(t
, RSTRING_PTR(str
), s
- RSTRING_PTR(str
));
2845 t
+= s
- RSTRING_PTR(str
);
2848 c
= rb_enc_ascget(s
, send
, &clen
, enc
);
2850 int n
= mbclen(s
, send
, enc
);
2858 case '[': case ']': case '{': case '}':
2859 case '(': case ')': case '|': case '-':
2860 case '*': case '.': case '\\':
2861 case '?': case '+': case '^': case '$':
2892 rb_str_resize(tmp
, t
- RSTRING_PTR(tmp
));
2893 OBJ_INFECT(tmp
, str
);
2900 * Regexp.escape(str) => string
2901 * Regexp.quote(str) => string
2903 * Escapes any characters that would have special meaning in a regular
2904 * expression. Returns a new escaped string, or self if no characters are
2905 * escaped. For any string,
2906 * <code>Regexp.new(Regexp.escape(<i>str</i>))=~<i>str</i></code> will be true.
2908 * Regexp.escape('\*?{}.') #=> \\\*\?\{\}\.
2913 rb_reg_s_quote(VALUE c
, VALUE str
)
2915 return rb_reg_quote(reg_operand(str
, Qtrue
));
2919 rb_reg_options(VALUE re
)
2924 options
= RREGEXP(re
)->ptr
->options
& ARG_REG_OPTION_MASK
;
2925 if (RBASIC(re
)->flags
& KCODE_FIXED
) options
|= ARG_ENCODING_FIXED
;
2926 if (RBASIC(re
)->flags
& REG_ENCODING_NONE
) options
|= ARG_ENCODING_NONE
;
2931 rb_check_regexp_type(VALUE re
)
2933 return rb_check_convert_type(re
, T_REGEXP
, "Regexp", "to_regexp");
2938 * Regexp.try_convert(obj) -> re or nil
2940 * Try to convert <i>obj</i> into a Regexp, using to_regexp method.
2941 * Returns converted regexp or nil if <i>obj</i> cannot be converted
2944 * Regexp.try_convert(/re/) #=> /re/
2945 * Regexp.try_convert("re") #=> nil
2948 * Regexp.try_convert(o) #=> nil
2949 * def o.to_regexp() /foo/ end
2950 * Regexp.try_convert(o) #=> /foo/
2954 rb_reg_s_try_convert(VALUE dummy
, VALUE re
)
2956 return rb_check_regexp_type(re
);
2960 rb_reg_s_union(VALUE self
, VALUE args0
)
2962 long argc
= RARRAY_LEN(args0
);
2966 args
[0] = rb_str_new2("(?!)");
2967 return rb_class_new_instance(1, args
, rb_cRegexp
);
2969 else if (argc
== 1) {
2970 VALUE arg
= rb_ary_entry(args0
, 0);
2971 VALUE re
= rb_check_regexp_type(arg
);
2976 quoted
= rb_reg_s_quote(Qnil
, arg
);
2977 return rb_reg_new_str(quoted
, 0);
2982 VALUE source
= rb_str_buf_new(0);
2983 rb_encoding
*result_enc
;
2985 int has_asciionly
= 0;
2986 rb_encoding
*has_ascii_compat_fixed
= 0;
2987 rb_encoding
*has_ascii_incompat
= 0;
2989 for (i
= 0; i
< argc
; i
++) {
2991 VALUE e
= rb_ary_entry(args0
, i
);
2994 rb_str_buf_cat_ascii(source
, "|");
2996 v
= rb_check_regexp_type(e
);
2998 rb_encoding
*enc
= rb_enc_get(v
);
2999 if (!rb_enc_asciicompat(enc
)) {
3000 if (!has_ascii_incompat
)
3001 has_ascii_incompat
= enc
;
3002 else if (has_ascii_incompat
!= enc
)
3003 rb_raise(rb_eArgError
, "incompatible encodings: %s and %s",
3004 rb_enc_name(has_ascii_incompat
), rb_enc_name(enc
));
3006 else if (rb_reg_fixed_encoding_p(v
)) {
3007 if (!has_ascii_compat_fixed
)
3008 has_ascii_compat_fixed
= enc
;
3009 else if (has_ascii_compat_fixed
!= enc
)
3010 rb_raise(rb_eArgError
, "incompatible encodings: %s and %s",
3011 rb_enc_name(has_ascii_compat_fixed
), rb_enc_name(enc
));
3021 enc
= rb_enc_get(e
);
3022 if (!rb_enc_str_asciicompat_p(e
)) {
3023 if (!has_ascii_incompat
)
3024 has_ascii_incompat
= enc
;
3025 else if (has_ascii_incompat
!= enc
)
3026 rb_raise(rb_eArgError
, "incompatible encodings: %s and %s",
3027 rb_enc_name(has_ascii_incompat
), rb_enc_name(enc
));
3029 else if (rb_enc_str_asciionly_p(e
)) {
3033 if (!has_ascii_compat_fixed
)
3034 has_ascii_compat_fixed
= enc
;
3035 else if (has_ascii_compat_fixed
!= enc
)
3036 rb_raise(rb_eArgError
, "incompatible encodings: %s and %s",
3037 rb_enc_name(has_ascii_compat_fixed
), rb_enc_name(enc
));
3039 v
= rb_reg_s_quote(Qnil
, e
);
3041 if (has_ascii_incompat
) {
3042 if (has_asciionly
) {
3043 rb_raise(rb_eArgError
, "ASCII incompatible encoding: %s",
3044 rb_enc_name(has_ascii_incompat
));
3046 if (has_ascii_compat_fixed
) {
3047 rb_raise(rb_eArgError
, "incompatible encodings: %s and %s",
3048 rb_enc_name(has_ascii_incompat
), rb_enc_name(has_ascii_compat_fixed
));
3053 rb_enc_copy(source
, v
);
3055 rb_str_append(source
, v
);
3058 if (has_ascii_incompat
) {
3059 result_enc
= has_ascii_incompat
;
3061 else if (has_ascii_compat_fixed
) {
3062 result_enc
= has_ascii_compat_fixed
;
3065 result_enc
= rb_ascii8bit_encoding();
3068 rb_enc_associate(source
, result_enc
);
3069 return rb_class_new_instance(1, &source
, rb_cRegexp
);
3075 * Regexp.union(pat1, pat2, ...) => new_regexp
3076 * Regexp.union(pats_ary) => new_regexp
3078 * Return a <code>Regexp</code> object that is the union of the given
3079 * <em>pattern</em>s, i.e., will match any of its parts. The <em>pattern</em>s
3080 * can be Regexp objects, in which case their options will be preserved, or
3081 * Strings. If no patterns are given, returns <code>/(?!)/</code>.
3083 * Regexp.union #=> /(?!)/
3084 * Regexp.union("penzance") #=> /penzance/
3085 * Regexp.union("a+b*c") #=> /a\+b\*c/
3086 * Regexp.union("skiing", "sledding") #=> /skiing|sledding/
3087 * Regexp.union(["skiing", "sledding"]) #=> /skiing|sledding/
3088 * Regexp.union(/dogs/, /cats/i) #=> /(?-mix:dogs)|(?i-mx:cats)/
3091 rb_reg_s_union_m(VALUE self
, VALUE args
)
3094 if (RARRAY_LEN(args
) == 1 &&
3095 !NIL_P(v
= rb_check_array_type(rb_ary_entry(args
, 0)))) {
3096 return rb_reg_s_union(self
, v
);
3098 return rb_reg_s_union(self
, args
);
3103 rb_reg_init_copy(VALUE copy
, VALUE re
)
3105 onig_errmsg_buffer err
= "";
3109 if (copy
== re
) return copy
;
3110 rb_check_frozen(copy
);
3111 /* need better argument type check */
3112 if (!rb_obj_is_instance_of(re
, rb_obj_class(copy
))) {
3113 rb_raise(rb_eTypeError
, "wrong argument type");
3116 s
= RREGEXP_SRC_PTR(re
);
3117 len
= RREGEXP_SRC_LEN(re
);
3118 if (rb_reg_initialize(copy
, s
, len
, rb_enc_get(re
), rb_reg_options(re
), err
) != 0) {
3119 rb_reg_raise(s
, len
, err
, re
);
3125 rb_reg_regsub(VALUE str
, VALUE src
, struct re_registers
*regs
, VALUE regexp
)
3130 rb_encoding
*str_enc
= rb_enc_get(str
);
3131 rb_encoding
*src_enc
= rb_enc_get(src
);
3132 int acompat
= rb_enc_asciicompat(str_enc
);
3133 #define ASCGET(s,e,cl) (acompat ? (*cl=1,s[0]) : rb_enc_ascget(s, e, cl, str_enc))
3135 p
= s
= RSTRING_PTR(str
);
3136 e
= s
+ RSTRING_LEN(str
);
3139 int c
= ASCGET(s
, e
, &clen
);
3143 s
+= mbclen(s
, e
, str_enc
);
3149 if (c
!= '\\' || s
== e
) continue;
3152 val
= rb_str_buf_new(ss
-p
);
3154 rb_enc_str_buf_cat(val
, p
, ss
-p
, str_enc
);
3156 c
= ASCGET(s
, e
, &clen
);
3158 s
+= mbclen(s
, e
, str_enc
);
3159 rb_enc_str_buf_cat(val
, ss
, s
-ss
, str_enc
);
3167 case '1': case '2': case '3': case '4':
3168 case '5': case '6': case '7': case '8': case '9':
3169 if (onig_noname_group_capture_is_active(RREGEXP(regexp
)->ptr
)) {
3178 if (s
< e
&& ASCGET(s
, e
, &clen
) == '<') {
3179 char *name
, *name_end
;
3181 name_end
= name
= s
+ clen
;
3182 while (name_end
< e
) {
3183 c
= ASCGET(name_end
, e
, &clen
);
3184 if (c
== '>') break;
3185 name_end
+= c
== -1 ? mbclen(name_end
, e
, str_enc
) : clen
;
3188 no
= name_to_backref_number(regs
, regexp
, name
, name_end
);
3189 p
= s
= name_end
+ clen
;
3193 rb_raise(rb_eRuntimeError
, "invalid group name reference format");
3197 rb_enc_str_buf_cat(val
, ss
, s
-ss
, str_enc
);
3206 rb_enc_str_buf_cat(val
, RSTRING_PTR(src
), BEG(0), src_enc
);
3210 rb_enc_str_buf_cat(val
, RSTRING_PTR(src
)+END(0), RSTRING_LEN(src
)-END(0), src_enc
);
3214 no
= regs
->num_regs
-1;
3215 while (BEG(no
) == -1 && no
> 0) no
--;
3216 if (no
== 0) continue;
3220 rb_enc_str_buf_cat(val
, s
-clen
, clen
, str_enc
);
3224 rb_enc_str_buf_cat(val
, ss
, s
-ss
, str_enc
);
3229 if (no
>= regs
->num_regs
) continue;
3230 if (BEG(no
) == -1) continue;
3231 rb_enc_str_buf_cat(val
, RSTRING_PTR(src
)+BEG(no
), END(no
)-BEG(no
), src_enc
);
3235 if (!val
) return str
;
3237 rb_enc_str_buf_cat(val
, p
, e
-p
, str_enc
);
3246 rb_warn("variable $KCODE is no longer effective");
3251 kcode_setter(VALUE val
, ID id
)
3253 rb_warn("variable $KCODE is no longer effective; ignored");
3257 ignorecase_getter(void)
3259 rb_warn("variable $= is no longer effective");
3264 ignorecase_setter(VALUE val
, ID id
)
3266 rb_warn("variable $= is no longer effective; ignored");
3272 VALUE match
= rb_backref_get();
3274 if (NIL_P(match
)) return Qnil
;
3275 rb_match_busy(match
);
3280 match_setter(VALUE val
)
3283 Check_Type(val
, T_MATCH
);
3285 rb_backref_set(val
);
3290 * Regexp.last_match => matchdata
3291 * Regexp.last_match(n) => str
3293 * The first form returns the <code>MatchData</code> object generated by the
3294 * last successful pattern match. Equivalent to reading the global variable
3295 * <code>$~</code>. The second form returns the <i>n</i>th field in this
3296 * <code>MatchData</code> object.
3297 * <em>n</em> can be a string or symbol to reference a named capture.
3299 * /c(.)t/ =~ 'cat' #=> 0
3300 * Regexp.last_match #=> #<MatchData "cat" 1:"a">
3301 * Regexp.last_match(0) #=> "cat"
3302 * Regexp.last_match(1) #=> "a"
3303 * Regexp.last_match(2) #=> nil
3305 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ "var = val"
3306 * Regexp.last_match #=> #<MatchData "var = val" lhs:"var" rhs:"val">
3307 * Regexp.last_match(:lhs) #=> "var"
3308 * Regexp.last_match(:rhs) #=> "val"
3312 rb_reg_s_last_match(int argc
, VALUE
*argv
)
3316 if (argc
> 0 && rb_scan_args(argc
, argv
, "01", &nth
) == 1) {
3317 VALUE match
= rb_backref_get();
3319 if (NIL_P(match
)) return Qnil
;
3320 n
= match_backref_number(match
, nth
);
3321 return rb_reg_nth_match(n
, match
);
3323 return match_getter();
3327 re_warn(const char *s
)
3333 * Document-class: Regexp
3335 * A <code>Regexp</code> holds a regular expression, used to match a pattern
3336 * against strings. Regexps are created using the <code>/.../</code> and
3337 * <code>%r{...}</code> literals, and by the <code>Regexp::new</code>
3345 rb_eRegexpError
= rb_define_class("RegexpError", rb_eStandardError
);
3347 onigenc_set_default_caseconv_table((UChar
*)casetable
);
3348 onigenc_set_default_encoding(ONIG_ENCODING_ASCII
);
3349 onig_set_warn_func(re_warn
);
3350 onig_set_verb_warn_func(re_warn
);
3352 rb_define_virtual_variable("$~", match_getter
, match_setter
);
3353 rb_define_virtual_variable("$&", last_match_getter
, 0);
3354 rb_define_virtual_variable("$`", prematch_getter
, 0);
3355 rb_define_virtual_variable("$'", postmatch_getter
, 0);
3356 rb_define_virtual_variable("$+", last_paren_match_getter
, 0);
3358 rb_define_virtual_variable("$=", ignorecase_getter
, ignorecase_setter
);
3359 rb_define_virtual_variable("$KCODE", kcode_getter
, kcode_setter
);
3360 rb_define_virtual_variable("$-K", kcode_getter
, kcode_setter
);
3362 rb_cRegexp
= rb_define_class("Regexp", rb_cObject
);
3363 rb_define_alloc_func(rb_cRegexp
, rb_reg_s_alloc
);
3364 rb_define_singleton_method(rb_cRegexp
, "compile", rb_class_new_instance
, -1);
3365 rb_define_singleton_method(rb_cRegexp
, "quote", rb_reg_s_quote
, 1);
3366 rb_define_singleton_method(rb_cRegexp
, "escape", rb_reg_s_quote
, 1);
3367 rb_define_singleton_method(rb_cRegexp
, "union", rb_reg_s_union_m
, -2);
3368 rb_define_singleton_method(rb_cRegexp
, "last_match", rb_reg_s_last_match
, -1);
3369 rb_define_singleton_method(rb_cRegexp
, "try_convert", rb_reg_s_try_convert
, 1);
3371 rb_define_method(rb_cRegexp
, "initialize", rb_reg_initialize_m
, -1);
3372 rb_define_method(rb_cRegexp
, "initialize_copy", rb_reg_init_copy
, 1);
3373 rb_define_method(rb_cRegexp
, "hash", rb_reg_hash
, 0);
3374 rb_define_method(rb_cRegexp
, "eql?", rb_reg_equal
, 1);
3375 rb_define_method(rb_cRegexp
, "==", rb_reg_equal
, 1);
3376 rb_define_method(rb_cRegexp
, "=~", rb_reg_match
, 1);
3377 rb_define_method(rb_cRegexp
, "===", rb_reg_eqq
, 1);
3378 rb_define_method(rb_cRegexp
, "~", rb_reg_match2
, 0);
3379 rb_define_method(rb_cRegexp
, "match", rb_reg_match_m
, -1);
3380 rb_define_method(rb_cRegexp
, "to_s", rb_reg_to_s
, 0);
3381 rb_define_method(rb_cRegexp
, "inspect", rb_reg_inspect
, 0);
3382 rb_define_method(rb_cRegexp
, "source", rb_reg_source
, 0);
3383 rb_define_method(rb_cRegexp
, "casefold?", rb_reg_casefold_p
, 0);
3384 rb_define_method(rb_cRegexp
, "options", rb_reg_options_m
, 0);
3385 rb_define_method(rb_cRegexp
, "encoding", rb_obj_encoding
, 0); /* in encoding.c */
3386 rb_define_method(rb_cRegexp
, "fixed_encoding?", rb_reg_fixed_encoding_p
, 0);
3387 rb_define_method(rb_cRegexp
, "names", rb_reg_names
, 0);
3388 rb_define_method(rb_cRegexp
, "named_captures", rb_reg_named_captures
, 0);
3390 rb_define_const(rb_cRegexp
, "IGNORECASE", INT2FIX(ONIG_OPTION_IGNORECASE
));
3391 rb_define_const(rb_cRegexp
, "EXTENDED", INT2FIX(ONIG_OPTION_EXTEND
));
3392 rb_define_const(rb_cRegexp
, "MULTILINE", INT2FIX(ONIG_OPTION_MULTILINE
));
3394 rb_global_variable(®_cache
);
3396 rb_cMatch
= rb_define_class("MatchData", rb_cObject
);
3397 rb_define_alloc_func(rb_cMatch
, match_alloc
);
3398 rb_undef_method(CLASS_OF(rb_cMatch
), "new");
3400 rb_define_method(rb_cMatch
, "initialize_copy", match_init_copy
, 1);
3401 rb_define_method(rb_cMatch
, "regexp", match_regexp
, 0);
3402 rb_define_method(rb_cMatch
, "names", match_names
, 0);
3403 rb_define_method(rb_cMatch
, "size", match_size
, 0);
3404 rb_define_method(rb_cMatch
, "length", match_size
, 0);
3405 rb_define_method(rb_cMatch
, "offset", match_offset
, 1);
3406 rb_define_method(rb_cMatch
, "begin", match_begin
, 1);
3407 rb_define_method(rb_cMatch
, "end", match_end
, 1);
3408 rb_define_method(rb_cMatch
, "to_a", match_to_a
, 0);
3409 rb_define_method(rb_cMatch
, "[]", match_aref
, -1);
3410 rb_define_method(rb_cMatch
, "captures", match_captures
, 0);
3411 rb_define_method(rb_cMatch
, "values_at", match_values_at
, -1);
3412 rb_define_method(rb_cMatch
, "pre_match", rb_reg_match_pre
, 0);
3413 rb_define_method(rb_cMatch
, "post_match", rb_reg_match_post
, 0);
3414 rb_define_method(rb_cMatch
, "to_s", match_to_s
, 0);
3415 rb_define_method(rb_cMatch
, "inspect", match_inspect
, 0);
3416 rb_define_method(rb_cMatch
, "string", match_string
, 0);