Using Regular Expressions in Ruby
May 14, 2014
Bài viết dưới đây sẽ nêu một vài ví dụ điển hình hay gặp khi sử dụng Regular Expression trong Ruby
1. Cú pháp
- Bạn có thể check cấu trúc của chuỗi bất kì giữa hai dấu
/ search string /
2. Ví dụ kiểm tra xâu kí tự đơn giản
Một số ví dụ hay gặp để kiểm tra một số mẫu string nhất định
- Kiểm tra cơ bản
text =~ /Ruby/ # Match for an unbound literal text =~ /^Ruby/ # Match literal at start of string text =~ /Ruby$/ # Match literal at end of string text =~ /^Ruby$/ # Match for exact string content text =~ /^$/ # Match empty string
%r/Ruby/ # / as commonly used delimiter %r@Ruby@ # @ as delimiter %r!Ruby! # ! as delimiter
text =~ /Ruby/ # case sensitive string matching text =~ /ruby/i # case in-sensitive string matching
"Ruby" =~ /R..y/ # match a single character with . "Ruby" =~ /R.*y/ # match multipe characters "Ruby" =~ /R[a-z]y/ # match from character range a-z "Rbuy" =~ /[Ruby]*/ # match from character set R,u,b and y "Ruby" =~ /R\wy/ # match one word character "regex in Ruby" =~ /\bRuby\b/" # match the word "Ruby", but not "Ruby" as larger string
"Ruby" =~ /[Ruby]{4}/ # match exactly 4 characters from set [Ruby] "Ruby" =~ /[Ruby]{4,4}/ # match exactly 4 characters from set [Ruby] "Ruby" =~ /[Ruby]{,3}/ # match at most 3 characters from set [Ruby] "Ruby" =~ /[Ruby]{3,}/ # match at least 3 characters from set [Ruby]
Bạn có thể thay thế các string con trong chuỗi string với cấu trúc nhất định bằng một chuỗi string khác bằng các sử dụng regular expression trong sub! (để thay thế toàn bộ các sub string) và gsub! (thay thế sub string đầu tiên)
text.sub!(/Rbuy/, "Ruby")
# Extract everything after the literal "START" if result = line.match(/START(.*)/") text = result.captures end # Extract the number from a date string "2012-10-20" if result = line.match(/(\d{4})-(\d{2})-(\d{2})/) year, week, day = result.captures end # Nesting of capture groups, extract full name, and both parts... string "name is Doe, John" if result = line.match(/name is ((\w+), (\w+))/) fullname, firstname, lastname = result.capture end
Đối với các kí tự đặc biệt như (+ ? . * ^ $ ( ) [ ] { } | \)
bạn có thể sử dụng với kí tự \
đằng trước nó
Bảng dưới đây là một số mẫu hay dùng trong Ruby Regular Expression
Pattern | Description |
---|---|
^ | Matches beginning of line. |
$ | Matches end of line. |
. | Matches any single character except newline. Using m option allows it to match newline as well. |
[…] | Matches any single character in brackets. |
[^…] | Matches any single character not in brackets |
re* | Matches 0 or more occurrences of preceding expression. |
re+ | Matches 1 or more occurrence of preceding expression. |
re? | Matches 0 or 1 occurrence of preceding expression. |
re{ n} | Matches exactly n number of occurrences of preceding expression. |
re{ n,} | Matches n or more occurrences of preceding expression. |
re{ n, m} | Matches at least n and at most m occurrences of preceding expression. |
a| b | Matches either a or b. |
(re) | Groups regular expressions and remembers matched text. |
(?imx) | Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected. |
(?-imx) | Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected. |
(?: re) | Groups regular expressions without remembering matched text. |
(?imx: re) | Temporarily toggles on i, m, or x options within parentheses. |
(?-imx: re) | Temporarily toggles off i, m, or x options within parentheses. |
(?#…) | Comment. |
(?= re) | Specifies position using a pattern. Doesn’t have a range. |
(?! re) | Specifies position using pattern negation. Doesn’t have a range. |
(?> re) | Matches independent pattern without backtracking. |
\w | Matches word characters. |
\W | Matches nonword characters. |
\s | Matches whitespace. Equivalent to [\t\n\r\f]. |
\S | Matches nonwhitespace. |
\d | Matches digits. Equivalent to [0-9]. |
\D | Matches nondigits. |
\A | Matches beginning of string. |
\Z | Matches end of string. If a newline exists, it matches just before newline. |
\z | Matches end of string. |
\G | Matches point where last match finished. |
\b | Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. |
\B | Matches nonword boundaries. |
\n, \t, etc. | Matches newlines, carriage returns, tabs, etc. |
\1…\9 | Matches nth grouped subexpression. |
\10 | Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code. |