【发布时间】:2016-08-22 18:34:07
【问题描述】:
在我的应用程序中,我有一个程序应该检查输入是否有效。您可以为此输入设置正则表达式。
但在我的情况下,它返回 false 而不是 true。而且我找不到问题。
我的代码如下所示:
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
一个例子是:
[[~berlin|berlin]]
管道前面的左边是正则表达式,管道旁边的右边是正确的解决方案。
这个简单的输入应该返回真,但它没有。
有人发现问题了吗?
谢谢大家
编辑
这行中的某个地方一定是问题所在:
if regex.include? "|"
puts "REGEX FOUND ------------------------------------------"
regex = regex.split("|")[0..-2].join("|")
end
reg = Regexp.new(regex, true)
unless reg.match(data[i])
更新:没有~的结果
【问题讨论】:
-
你能提供一个MVCE (minimal complete verifiable example)吗?也许,将问题缩小到什么不起作用。
-
那是在我的应用程序中间的某个地方。它周围有很多代码。我已经减少了那些代码行的问题
-
确切的输入是柏林,正则表达式应该对其进行测试 [[~berlin|berlin]] 管道左侧是我的正则表达式代码 - the
~berlinregex will never matchberlinpattern -
regex = regex.split("|")[0..-2].join("|")将导致regex等于[[berlin。您需要修剪[和]。 见this demo。
标签: ruby-on-rails ruby regex ruby-on-rails-4