[英]How to get a substring from the beginning till the end of a word that starts with a with a given substring - Ruby
在 Ruby 中,我試圖從以某個字符串開頭的單詞的開頭到結尾獲取一個子字符串。
例如:
a = "Metrics testSomeMetrics gets initial metrics data"
我也有一個字符串,它的一個子a
。
例如:
b = "test"
。
"test"
出現在字符串a
的第二個單詞中。
我需要從年初返回一個子a
,直到字的末尾test
它。
在這個例子中,我需要返回: "Metrics testSomeMetrics"
使用正則表達式:
a = 'Metrics testSomeMetrics gets initial metrics data'
b = 'test'
a.match(/^.*#{b}\w*/).to_s
在哪里:
^
— 字符串的開始。.*
— 零個或多個任何單個字符。#{b}
— 你的字符串。\\w*
— 零個或多個任意單詞字符。更新
添加\\b
以獲得/^.*\\b#{b}\\w*/
以便它b
將恰好是新字符串的開始。
我一直沒能找到一個在這里工作的正則表達式。 但是,可以執行以下操作:
def get_juicy_bit(str, word)
str.match(/\b#{word}\S+/) { |md| str[0...md.end(0)] }
end
word = "test"
get_juicy_bit("Metrics testSomeMetrics gets data", word)
#=> "Metrics testSomeMetrics"
get_juicy_bit("Metrics testSomeMetrics gets data", word)
#=> "Metrics testSomeMetrics"
get_juicy_bit("Metrics donottestMetrics gets data", word)
#=> nil
get_juicy_bit("testMetrics gets data", word)
#=> "testMetrics"
get_juicy_bit(" testMetrics gets data", word)
#=> " testMetrics"
請參閱MatchData#end 。 正則表達式/\\b#{word}\\S+/
讀作,“匹配一個分詞符 ( \\b
),后跟變量word
的值,后跟一個或多個非空格字符”。 此處的分詞符是除單詞字符(字母、數字或下划線)或字符串開頭以外的字符。
一種方法是:
首先,將您的字符串拆分為一組單詞。 然后找到包含該模式的第一個單詞的索引。 最后從找到的索引創建原始的子字符串(從 0 開始到找到的索引)。
a = "Metrics testSomeMetrics gets initial metrics data"
b = "test"
words = a.split(" ")
index = words.find_index { |word| word.include?(b) }
return "" unless index
words.slice(0..index).join(" ")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.