查找字符串左侧和右侧的单词

时间:2016-01-05 13:02:18

标签: ruby string

我希望将字词放在字符串的左侧和右侧。例如,如果整个字符串是:

"Programming is my passion"

我想提取"is"左侧和右侧的字词:"Programming""my"

7 个答案:

答案 0 :(得分:1)

\b(\w+) is (\w+)\b

现在参加比赛的第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+) - 包含在编号组中的尽可能多的单词字符

答案 1 :(得分:1)

这是一个解决方案;

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"

答案 2 :(得分:0)

您可以使用以下内容:

\b(\w+)\b\s+is\s+\b(\w+)\b
            ^^  

答案 3 :(得分:0)

您也可以使用此正则表达式:

(\S+)\s+is\s+(\S+)

DEMO:http://rubular.com/r/rAtgGuh7Oh

答案 4 :(得分:0)

带变量:

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

http://rubular.com/r/MvUFf9WVF7

答案 5 :(得分:0)

没有正则表达式但使用each_cons()的解决方案。

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')

答案 6 :(得分:0)

def neighbours str, pattern
  str.scan(/(\S*)\s+#{pattern}\s+(\S*)/).flatten
end

neighbours 'Programming is my passion', 'is'
#⇒ ["Programming", "my"]