Sha256: 0363f3453f5d228693d77333c5f5c77d586318c5ffd2b29607cc5872d3462d03

Contents?: true

Size: 772 Bytes

Versions: 4

Compression:

Stored size: 772 Bytes

Contents

# frozen_string_literal: true

module Srx
  # Utilities for handling SRX (ICU) regular expressions
  module IcuRegex
    HEX_PATTERN = /(?<!\\)(?:\\\\)*\\x(?<hex>\{[a-f0-9]{1,6}\})/i.freeze
    OCTAL_PATTERN = /(?<!\\)(?:\\\\)*\\0(?<oct>[0-7]{1,3})/i.freeze

    class << self
      # @param icu_regex [String]
      # @return [String]
      def to_ruby(icu_regex)
        result = icu_regex.dup
        result.gsub!(HEX_PATTERN, '\u\k<hex>')
        result.gsub!(OCTAL_PATTERN) do |m|
          $LAST_MATCH_INFO['oct'].to_i(8).then { |o| o <= 255 ? format(%q(\u{%x}), o) : m }
        end

        result
      end

      # @param icu_regex [String]
      # @return [Regexp]
      def compile(icu_regex)
        Regexp.new(to_ruby(icu_regex))
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
srx-0.6.0 lib/srx/icu_regex.rb
srx-0.5.0 lib/srx/icu_regex.rb
srx-0.4.0 lib/srx/icu_regex.rb
srx-0.3.0 lib/srx/icu_regex.rb