Q:

Ruby on Rails: Checking for valid regex does not work properly, high false rate

In my application I've got a procedure which should check if an input is valid or not. You can set up a regex for this input.
But in my case it returns false instead of true. And I can't find the problem.
My code looks like this:
gaps.each_index do | i |
if gaps[i].first.starts_with? "~"
  # regular expression      
    begin
     regex = gaps[i].first[1..-1]
     # a pipe is used to seperate the regex from the solution-string
     if regex.include? "|"
       puts "REGEX FOUND ------------------------------------------"
       regex = regex.split("|")[0..-2].join("|")
     end
     reg = Regexp.new(regex, true)
     unless reg.match(data[i])
     puts "REGEX WRONGGGG -------------------"
     @wrong_indexes << i
     end
   rescue
  end
  else
   # normal string
   if data[i].nil? || data[i].strip != gaps[i].first.strip
     @wrong_indexes << i
    end      
  end

An example would be:
[[~berlin|berlin]] 

The left one before the pipe is the regex and the right one next to the pipe is the correct solution. 
This easy input should return true, but it doesn't.
Does anyone see the problem?
Thank you all
EDIT
Somewhere in this lines must be the problem:
if regex.include? "|"
   puts "REGEX FOUND ------------------------------------------"
   regex = regex.split("|")[0..-2].join("|")
 end
 reg = Regexp.new(regex, true)
 unless reg.match(data[i])

Update: Result without ~ 

A:

The whole point is that you are initializing regex using the Regexp constructor

Constructs a new regular expression from pattern, which can be either a String or a Regexp (in which case that regexp’s options are propagated, and new options may not be specified (a change as of Ruby 1.8).

However, when you pass the regex (obtained with regex.split("|")[0..-2].join("|")) to the constructor, it is a string, and reg = Regexp.new(regex, true) is getting ~berlin (or /berlin/i) as a literal string pattern. Thus, it actually is searching for something you do not expect.
See, regex= "[[/berlin/i|berlin]]" only finds a *literal /berlin/i text (see demo).
Also, you need to get the pattern from the [[...]], so strip these brackets with regex = regex.gsub(/\A\[+|\]+\z/, '').split("|")[0..-2].join("|").
Note you do not need to specify the case insensitive options, since you already pass true as the second parameter to Regexp.new, it is already case-insensitive.
If you are performing whole word lookup, add word boundaries: regex= "[[\\bberlin\\b|berlin]]" (see demo).

