Ruby 查找字符串左右两侧的单词
我想把单词放在字符串的左边和右边。例如,如果整个字符串为:Ruby 查找字符串左右两侧的单词,ruby,string,Ruby,String,我想把单词放在字符串的左边和右边。例如,如果整个字符串为: "Programming is my passion" 我想提取“is”:“Programming”和“my”左右两侧的单词 现在以比赛的第1组和第2组为例 sentence = 'Programming is my passion' word = 'is' matches = sentence.match(/\b(\w+) #{word} (\w+)\b/) matches[1] # => "Programming
"Programming is my passion"
我想提取“is”
:“Programming”
和“my”
左右两侧的单词
现在以比赛的第1组和第2组为例
sentence = 'Programming is my passion'
word = 'is'
matches = sentence.match(/\b(\w+) #{word} (\w+)\b/)
matches[1] # => "Programming"
matches[2] # => "my"
这个想法是:
-单词边界\b
-在一个编号组中包含尽可能多的单词字符(\w+)
\b(\w+)\b\s+is\s+\b(\w+)\b
^^
您也可以使用此正则表达式:
(\S+)\s+is\s+(\S+)
演示:带变量:
string = 'Programming is my passion'
matchers = string.match(/(?<before>\w+)?\s?is\s?(?<after>\w*)?/)
matchers[:before] # "Programming"
matchers[:after] # "my"
string = 'Programmingismy passion'
# same tesults
string='编程是我的爱好'
matchers=string.match(/(?\w+)\s?是\s?(?这里有一个解决方案
str = "Programming is my passion"
word = "is"
words = str.split(/\W/)
index = words.index(word)
before, after = words[index-1], words[index+1] if index > 0
p before
#=> "Programming"
p after
#=> "my"
一种没有正则表达式但具有
如果句子改为“编程是我的爱好,因为它非常有趣”
,因为现在句子中有两个“是”的实例,那么这个函数应该如何工作呢
str = "Programming is my passion"
word = "is"
words = str.split(/\W/)
index = words.index(word)
before, after = words[index-1], words[index+1] if index > 0
p before
#=> "Programming"
p after
#=> "my"
str = "Programming is my passion"
def neighbors(s, w)
s.split(/\W/)
.each_cons(3)
.find { |_,e,_| e == w }
.reject { |e| e == w }
end
before, after = neighbors(str, 'is')
def neighbours str, pattern
str.scan(/(\S*)\s+#{pattern}\s+(\S*)/).flatten
end
neighbours 'Programming is my passion', 'is'
#⇒ ["Programming", "my"]