carlos quintero
carlos quintero

Reputation: 13

RegExp match fail in Ruby

I've got a problem with a chatbot in Ruby, there's a command for ban users, and it's supossed to work like writing on the chat

!ban [Username (the username sometimes may have blank spaces)] [Length of the ban in seconds] [Reason]

like

!ban Chara Cipher 3600 making flood

and the code is like

match /^ban (.*)(^0-9) (.+)/, :method => :ban


# @param [User] user
   # @param [String] target
   # @param [Integer] length
   # @param [String] reason
  def ban(user, target, length, reason)
    if user.is? :mod
      @client.ban(target, length, reason)
      @client.send_msg "#{target} ha sido baneado gracias a la magia de la amistad."
    end
  end

The problem is that the arguments don't match correctly with every string, maybe because the Regular Expression match part, (.*)(^0-9) (.+).

Does somebody know how to fix it?

Update https://gist.github.com/carlosqh2/b926e59772e3c28d104d756589acc75e#file-admin-rb-L213 line 214, 255-263, from Admin.rb and line 188 from client.rb are the most relevant lines, also, in lines 202-213 from Admin.rb the "!" is required for the commands to work in the chat

Upvotes: 0

Views: 264

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

I don't think (^0-9) does what you think it does. In regex it means "capture the literal characters '0-9' at the start of the current line.

Meditate on this:

" 0-9"[/(^0-9)/] # => nil
"0-9"[/(^0-9)/] # => "0-9"
" \n0-9"[/(^0-9)/] # => 
"0-9"

The last one matched the new-line along with 0-9 and returned those, causing the output to fall on the next line.

Instead you probably want [^0-9] which means "a character that is not 0-9" and will match correctly in the middle of strings:

" 0-9"[/[^0-9]/] # => " "
"0-9"[/[^0-9]/] # => "-"
" \n0-9"[/[^0-9]/] # => " "

Read the Regexp documentation and you can piece this all together.

Upvotes: 0

Jack Noble
Jack Noble

Reputation: 2098

Three issues I see. First, you're matching 'ban' not '!ban'. Second, the first match will just match the entire rest of the string including the time of ban and reason. Third, the pattern for second match is wrong. I suggest explicitly matching the spaces to delimit arguments like ^!ban\s(.+)\s(\d+)\s(.+).

Upvotes: 1

Related Questions