Skip to content

Instantly share code, notes, and snippets.

@hall757
Created September 15, 2023 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hall757/bd9c47e5dbeda37693124109c349aac4 to your computer and use it in GitHub Desktop.
Save hall757/bd9c47e5dbeda37693124109c349aac4 to your computer and use it in GitHub Desktop.
Combine one or more inclusion regex with one or more exclusion regex to form a single exclusion regex.

Make Exclusion Regular Expression

Combine one or more inclusion regex with one or more exclusion regex to form a single exclusion regex. This is based on a negative forward lookup to turn an inclusion into an exclusion.

  • ^((?!( regexp_to_invert )).)*$
  # takes single regexp as string or multiple as array, or nil
  def make_exclusion_regexp(i,e) # include,exclude

    i=[i] unless i.class==Array
    i=i.reject{|x|x.nil? or x.empty?}
    i=['.*'] if i.size==0
    
    e=[e] unless e.class==Array
    e=e.reject{|x|x.nil? or x.empty?}

    # turns the include list into an exclude list by using a negative forward
    # lookup.
    inverted_inclusion="^((?!("+i.join("|")+")).)*$"
    
    # add our new exclusion to exclusion array
    e.push(inverted_inclusion)
    
    return "("+e.join("|")+")"
  end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment