I am using Ruby 1.9.3. Just going thorugh the Ruby tutorials. Now I just got stuck to a statement on which regular expression is working and giving out put also. But confusion with the \/ operators logic.
RegExp-1
Today's date is: 1/15/2013. (String)
(?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4}) (Expression)
RegExp-2
s = 'a' * 25 + 'd' 'a' * 4 + 'c' (String)
/(b|a+)*\/ =~ s #=> ( expression)
Now couldn’t understand how \/ and =~ operator works in Ruby.
Could anyome out of here help me to understand the same?
Thanks
\serves as an escape character. In this context, it is used to indicate that the next character is a normal one and should not serve some special function. normally the/would end the regex, as regex’s are bookended by the/. but preceding the/with a\basically says “i’m not telling you to end the regex when I use this/, i want that as part of the regex.”As Lee pointed out, your second regex is invalid, specifically because you never end the regex with a proper
/. you escape the last/so that it’s just a plaintext character, so the regex is hanging. it’s like doingstr = "hello.as another example, normally
^is used in regex to indicate the beginning of a string, but doing\^means you just want to use the^character in the regex.=~says “does the regex match the string?” If there is a match, it returns the index of the start of the match, otherwise returnsnil. See this question for details.EDIT: Note that the
?<month>,?<day>,?<year>stuff is grouping. seems like you could use a bit of brush-up on regex, check out this appendix of sorts to see what all the different special characters do.