Module: RubyNext::Core::StringStripSelectors

Defined in:
lib/ruby-next/core/string/strip.rb

Class Method Summary collapse

Class Method Details

.build_pattern(selectors) ⇒ Object

Converts selector strings (like "0-9", "^a-z", "abc") into a regex character class pattern. For multiple selectors, we need to handle intersection/negation



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/ruby-next/core/string/strip.rb', line 91

def self.build_pattern(selectors)
  selectors.each { |selector| raise TypeError, "no implicit conversion of #{selector} into String" unless selector.respond_to?(:to_str) }

  if selectors.length == 1
    selector = selectors[0].to_str
    if selector.start_with?("^")
      char_class = escape_for_char_class(selector[1..-1])
      "[^#{char_class}]"
    elsif !selector.empty?
      char_class = escape_for_char_class(selector)
      "[#{char_class}]"
    end
  else
    positive = []
    negative = []

    selectors.each do |s|
      str = s.to_str
      if str.start_with?("^")
        negative << escape_for_char_class(str[1..-1])
      elsif !str.empty?
        positive << escape_for_char_class(str)
      end
    end

    if positive.any? && negative.any?
      pos_class = positive.join
      neg_class = negative.join
      "[#{pos_class}&&[^#{neg_class}]]"
    elsif positive.any?
      "[#{positive.join}]"
    elsif negative.any?
      "[^#{negative.join}]"
    end
  end
end

.escape_for_char_class(selector) ⇒ Object



128
129
130
131
132
133
134
135
# File 'lib/ruby-next/core/string/strip.rb', line 128

def self.escape_for_char_class(selector)
  str = selector.to_str

  # Escape special characters but preserve ranges
  # Inside character class: need to escape ] \ ^
  # - is special only between characters (part of range)
  str.gsub(/(?<!^)([\]\\\^])/) { "\\#{$1}" }
end