1

I am struggling to write a Ruby regexp that will match all words which: starts with 2 or 3 letters, then have backslash (\) and then have 7 or 8 letters and digits. The expression I use is like this:

p "BFD\082BBSA".match %r{\A[a-zA-Z]{2,3}\/[a-zA-Z0-9]{7,8}\z}

But each time this code returns nil. What am I doing wrong?

toro2k
  • 18,715
  • 7
  • 60
  • 69
Kerozu
  • 643
  • 5
  • 15

3 Answers3

4

Try as below :

'BFD\082BBSA'.match %r{\A[a-zA-Z]{2,3}\\[a-zA-Z0-9]{7,8}\z} 
 # => #<MatchData "BFD\\082BBSA">
 #or
"BFD\\082BBSA".match %r{\A[a-zA-Z]{2,3}\\[a-zA-Z0-9]{7,8}\z}
 # => #<MatchData "BFD\\082BBSA">

Read this also - Backslashes in Single quoted strings vs. Double quoted strings in Ruby?

Community
  • 1
  • 1
Arup Rakshit
  • 113,563
  • 27
  • 250
  • 306
2

The problem is that you actually have no backslash in your string, just a null Unicode character:

"BFD\082BBSA"
# => "BFD\u000082BBSA"

So you just have to escape the backslash in the string:

"BFD\\082BBSA"
# => "BFD\\082BBSA"

Moreover, as others pointed out, \/ will match a forward slash, so you have to change \/ into \\:

"BFD\\082BBSA".match(/\A[a-z]{2,3}\\[a-z0-9]{7,8}\z/i)
# => #<MatchData "BFD\\082BBSA">
toro2k
  • 18,715
  • 7
  • 60
  • 69
1

You wanted to match the backward slash, but you are matching forward slash. Please change the RegEx to

[a-zA-Z]{2,3}\\[a-zA-Z0-9]{7,8}

Note the \\ instead of \/. Check the RegEx at work, here

thefourtheye
  • 221,210
  • 51
  • 432
  • 478