在Ruby中,你可以使用String#include?
方法來檢查一個字符串是否包含另一個子串。這是一個簡單的例子:
str = "Hello, I am a Ruby programmer."
substring = "Ruby"
if str.include?(substring)
puts "The string contains the substring."
else
puts "The string does not contain the substring."
end
如果你想要查找子串的起始和結束位置,可以使用String#index
和String#rindex
方法。index
方法返回子串第一次出現的位置,而rindex
方法返回子串最后一次出現的位置。如果子串不存在,這些方法會返回nil
。
下面是一個例子:
str = "Hello, I am a Ruby programmer."
substring = "Ruby"
start_index = str.index(substring)
end_index = str.rindex(substring)
if start_index
puts "The substring starts at index #{start_index} and ends at index #{end_index - 1}."
else
puts "The substring is not found."
end
如果你需要更復雜的子串查找,例如查找所有匹配項或按正則表達式查找,可以使用String#scan
方法。這個方法接受一個正則表達式作為參數,并返回一個包含所有匹配項的數組。
下面是一個例子:
str = "There are 3 cats, 2 dogs, and 1 parrot."
pattern = /\d+/
matches = str.scan(pattern)
puts "Matches: #{matches.join(', ')}"
這個例子將輸出:
Matches: 3, 2, 1