ruby 中的正则表达式

摘录几个 ruby 正则表达式

# bad
hex_pattern = \
  /^(0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f)+$/
  
# Valid matches
"123abd" =~ hex_pattern #=> 0
"456789" =~ hex_pattern #=> 0

# Invalid, not hex characters
"876jkl" =~ hex_pattern #=> nil
  
# good
hex_pattern = /^[0-9a-f]+$/
message = <<-MESSAGE
The original idea came from @r00k,
then @christoomey did a first pass,
and @jferris came through to help
clean up the implementation.
MESSAGE

username_pattern = /@\w+/

message.scan(username_pattern)
#=> ["@r00k", "@christoomey", "@jferris"]
string = "The %start% and %end% of the content..."

# .*
string.scan(/%.*%/)
#=> ["%start% and %end%"]

# .*? 
string.scan(/%.*?%/)
#=> ["%start%", "%end%"]
# bad
/https:\/\/.*?\/api\/(.*?)\/(.*?)/

# good
%r{https://.*?/api/(.*?)/(.*?)}
# bad
/[0-9]+[ \t\r\n\f][a-zA-Z0-9_]*/

# good
/\d+\s\w*/
.     Any character except a newline
\w  A word character ([a-zA-Z0-9_])
\W  A non-word character ([^a-zA-Z0-9_])
\d  A digit character ([0-9])
\D  A non-digit character ([^0-9])
\h  A hex digit character ([0-9a-fA-F])
\H  A non-hex digit character ([^0-9a-fA-F])
\s  A whitespace character: ([ \t\r\n\f])
\S  A non-whitespace character: ([^ \t\r\n\f])
string = <<-STRING
The word class is a reserved word,
but we can use other words that
contain it, like "class_name", or
"klass" to work around this.
STRING

pattern = /\b[ck]lass\b/

string.scan(pattern)
#=> ["class", "klass"]
sample = \
  "{ count: 2, title: 'Hello', section: 3 }"

sample.scan(/\w+(?=:)/)
#=> ["count", "title", "section"]
valid_email = /.+@.+\..+/

possible_emails = [
  "[email protected]",
  "person@thing",
  "[email protected]",
  "[email protected]",
  "asdf"
]

possible_emails.grep(valid_email)
#=> [
#     "[email protected]",
#     "[email protected]",
#     "[email protected]"
#   ]

# Array#grep is essentially a shorthand for:
possible_emails.filter do |email|
  email =~ pattern
end
# 把句子中的 10/8/14 变成 Monday Aug 8
require "date"

sample = <<-SAMPLE
The first battle was on 10/8/14,
followed by additional skirmishes
on 11/9/14 and 11/12/14.
SAMPLE

date_pattern = %r{\d+/\d+/\d+}

sample.gsub(date_pattern) do |date|
  Date.
    strptime(date, "%m/%d/%y").
    strftime("%A %b %-d")
end

You Can't Parse HTML With Regex.

新添:

# 去空格及一些特殊字符
str.gsub(/\s|\\|\'|\/|\?/, "") if params[:q].present?

# 仅拿出字符串中的数字及大小写字母
str.gsub(/[^0-9A-Za-z]/, "")

你可能感兴趣的:(ruby 中的正则表达式)