user3472065
user3472065

Reputation: 1389

Check if a string contains a specific sequence of characters in Ruby

I'm trying to check if a string contains a specific sequence of characters. More precisely, I need to verify if my string has these characters:

A00[a-zA-Z]

So, I have a fixed part "A00" followed by one letter [a-zA-Z]. I have to identify if my "filename" string contains this sequence

filename -> A01k-test.rb   [KO]
filename -> A00W-test.rb   [OK]

I tried with this code

if @filename !~ /A00+[a-zA-Z]+$/;
    puts "OOOOOOOOOOK"
end

This code is not working, it doesn't match correctly.

Upvotes: 1

Views: 818

Answers (1)

Arie Xiao
Arie Xiao

Reputation: 14082

!~ (do not match) is the inverse of =~ (match). You need to use the later for a match.

$ is an anchor for the end-of-line or end-of-string in Ruby regular expression, which you don't need according to your post.

Try:

if @filename =~ /A00[a-zA-Z]/
  puts "OOOOOOOOOOK"
end

Upvotes: 3

Related Questions