I-am-simple-user I-am-simple-user - 5 months ago 41
Ruby Question

Check whether a string contains / (forward slash) or \ (backward slash) using regex

How can I find the string, that contains / (forward slash) or \ (backward slash) or both using Regexp?

Ex. I have following array

['ABC', 'abc/sd', dsa\adf', as/\sfd', ball, cat]

then it will return only those strings that contain slash.


You have to escape them in the regex. Try

a = ['ABC', 'abc/sd', 'dsa\adf', 'as/\sfd', 'ball', 'cat']
a.select { |s| s.match(/[\/\\]/) }
 => ["abc/sd", "dsa\\adf", "as/\\sfd"]