Ruby used to learn a lot from perl, one of which is the global magic variable. Among these variables, it is estimated that no $ _ is more strange. For example, the gets method has this effect: while returning the row data you just read, it also saves the row data to $ _. if you call the print method without parameters, it prints the content in $. If you use only one regular expression as a condition when writing an if or while statement, the regular expression automatically matches $ _. in this case, we can write the following short and concise program to find the rows containing the email address in all the rows. 1 while gets
2 if/[a-zA-Z0-9 \. \-_] @ [a-zA-Z0-9 \. \-_]/
3 print
4 end
5end
6
However, this is not concise for Ruby. We can use ARGF. each {| line | print line if line = ~ /[A-zA-Z0-9 \. \-_] @ [a-zA-Z0-9 \. \-_]/}
Haha, what's the matter? I'm surprised. A statement is done, and ruby is efficient!
There is also a global variable, $. which contains the total number of lines of the file.
Other global variables $ &, & ', &' are used in regular expressions.
When you use match or = ~ When matching a string and a regular expression, the result is: $ & stores the part of the string that matches the regular expression, $ 'stores the previous string in the $ & part of the string, $ 'stores the last string of $ & in the string.
For example
Str = "good day! Woodfish1988@163.com It's a email"
Reg =/[a-zA-Z0-9 \-\. _] + @ [a-zA-Z0-9 \-\. _] +/
Reg = ~ Str
Puts $ ', $ &, $'
The result is
Good day!
Woodfish1988@163.com
It's a email
At the same time, the global scalar $1 after matching .. $9 contains small content that matches the regular expression (that is, the content enclosed by brackets). For details, see the regular expression tutorial)
For example:
Code = "<a href = 'HTTP: // www.google.com '> Google </a>"
Reg =/<a href = '(. +)'> (. +) <\/a>/
Reg = ~ Code
Puts $1, $2
The result is
Http://www.google.com
Google