不知道为什么这个简单的正则表达式匹配代码不起作用

时间:2015-10-30 01:30:04

标签: ruby regex

# #!/usr/local/bin/ruby

puts "why doesn't this work??"
pi = ''
special = "[;\`'<>-]"
regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/

pi = ARGV[0].to_s #takes in console argument to test

if pi == '3.1415926535897932385'
  puts "got it"
end
if pi =~ regex
  puts "stop word"
else 
  puts "incorrect"
end

我要做的就是测试pi变量是否包含任何停止字符,如果为true,则打印“停止字”,否则分别得到或不正确。我尝试过这十种方式。扫描,包括?线条,我觉得这是最好的路线。

2 个答案:

答案 0 :(得分:1)

我认为你可能会过度思考这个问题。以下是两种方式(在众多方面),其中true表示字符串至少包含一个特殊字符):

<强>#1

baddies = "[;`'<>-]"

pi = '3.14'
pi.delete(baddies).size < pi.size #=> false

pi = '3.1;4'
pi.delete(baddies).size < pi.size #=> true

<强>#2

special = %w| [ ; ` ' < > - ] |
  # => ["[", ";", "`", "'", "<", ">", "-", "]"]

pi = '3.14'
(pi.chars & special).any? #=> false

pi = '3.1cat4'
(pi.chars & special).any? #=> false

pi = '3.1;4'
(pi.chars & special).any? #=> true

答案 1 :(得分:0)

您无需转义角色类中的任何字符:

special = "[;\`'<>-]"
regex = /#{special}/
p regex

#pi = ARGV[0]  #takes in console argument to test
pi = 'hello;world'

if pi == '3.1415926535897932385'
  puts "got it"
end

if pi =~ regex
  puts "stop word"
else 
  puts "incorrect"
end

--output:--
/[;`'<>-]/
stop word

ARGV[0]已经是一个字符串了。但是,当您在命令行输入时,shell /控制台也会识别特殊字符:

special = "[;\`'<>-]"
#regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/
regex = /#{special}/
p regex

pi = ARGV[0] #takes in console argument to test

if pi == '3.1415926535897932385'
  puts "got it"
end

if pi =~ regex
  puts "stop word"
else 
  puts "incorrect"
end

--output:--
~/ruby_programs$ ruby 1.rb ;
/[;`'<>-]/
incorrect

~/ruby_programs$ ruby 1.rb <
-bash: syntax error near unexpected token `newline'

如果您希望shell /控制台将其识别的特殊字符视为文字,则必须引用它们。 quote things in a shell/console有多种方式:

~/ruby_programs$ ruby 1.rb \;
/[;`'<>-]/
stop word

~/ruby_programs$ ruby 1.rb \<
/[;`'<>-]/
stop word

请注意,您也可以使用String#[]

special = "[;\`'<>-]"
regex = /#{special}/
...
...
if pi[regex]
  puts "stop word"
else 
  puts "incorrect"
end