溫馨提示×

Ruby字符串處理怎樣查找子串

小樊
91
2024-11-06 03:16:35
欄目: 編程語言

在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#indexString#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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女