String#byteindex
static VALUE
rb_str_byteindex_m(int argc, VALUE *argv, VALUE str)
{
VALUE sub;
VALUE initpos;
long pos;
if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) {
long slen = RSTRING_LEN(str);
pos = NUM2LONG(initpos);
if (pos < 0 ? (pos += slen) < 0 : pos > slen) {
if (RB_TYPE_P(sub, T_REGEXP)) {
rb_backref_set(Qnil);
}
return Qnil;
}
}
else {
pos = 0;
}
str_ensure_byte_pos(str, pos);
if (RB_TYPE_P(sub, T_REGEXP)) {
if (rb_reg_search(sub, str, pos, 0) >= 0) {
VALUE match = rb_backref_get();
struct re_registers *regs = RMATCH_REGS(match);
pos = BEG(0);
return LONG2NUM(pos);
}
}
else {
StringValue(sub);
pos = rb_str_byteindex(str, sub, pos);
if (pos >= 0) return LONG2NUM(pos);
}
return Qnil;
}
Returns the 0-based integer index of a substring of self specified by object (a string or Regexp) and offset, or nil if there is no such substring; the returned index is the count of bytes (not characters).
When object is a string, returns the index of the first found substring equal to object:
s = 'foo' # => "foo" s.size # => 3 # Three 1-byte characters. s.bytesize # => 3 # Three bytes. s.byteindex('f') # => 0 s.byteindex('o') # => 1 s.byteindex('oo') # => 1 s.byteindex('ooo') # => nil
When object is a Regexp, returns the index of the first found substring matching object; updates Regexp-related global variables:
s = 'foo' s.byteindex(/f/) # => 0 $~ # => #<MatchData "f"> s.byteindex(/o/) # => 1 s.byteindex(/oo/) # => 1 s.byteindex(/ooo/) # => nil $~ # => nil
Integer argument offset, if given, specifies the 0-based index of the byte where searching is to begin.
When offset is non-negative, searching begins at byte position offset:
s = 'foo' s.byteindex('o', 1) # => 1 s.byteindex('o', 2) # => 2 s.byteindex('o', 3) # => nil
When offset is negative, counts backward from the end of self:
s = 'foo' s.byteindex('o', -1) # => 2 s.byteindex('o', -2) # => 1 s.byteindex('o', -3) # => 1 s.byteindex('o', -4) # => nil
Raises IndexError if the byte at offset is not the first byte of a character:
s = "\uFFFF\uFFFF" # => "\uFFFF\uFFFF" s.size # => 2 # Two 3-byte characters. s.bytesize # => 6 # Six bytes. s.byteindex("\uFFFF") # => 0 s.byteindex("\uFFFF", 1) # Raises IndexError s.byteindex("\uFFFF", 2) # Raises IndexError s.byteindex("\uFFFF", 3) # => 3 s.byteindex("\uFFFF", 4) # Raises IndexError s.byteindex("\uFFFF", 5) # Raises IndexError s.byteindex("\uFFFF", 6) # => nil
Related: see Querying.
Ruby version changes
-
3.2
-
String#byteindexandString#byterindexhave been added. [Feature #13110]
-