I-am-simple-user I-am-simple-user - 1 year ago 154
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.

Answer Source

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"] 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download