sample_string = "let's could've they'll you're won't"
sample_string.scan(/w+/)
上面给我:
["let", "s", "could", "ve", "they", "ll", "you", "re", "won", "t"]
我想要的:
["let", "could", "they", "you", "won"]
一直在https://rubular.com/和尝试断言像w+(?<=')
,但没有运气。
给定:
> sample_string = "let's could've they'll you're won't"
你可以做分割和映射:
> sample_string.split.map{|w| w.split(/'/)[0]}
=> ["let", "could", "they", "you", "won"]
可以使用
sample_string.scan(/(?<![w'])w+/)
sample_string.scan(/b(?<!')w+/)
参见Rubular演示。模式(它们是绝对的同义词)匹配
(?<![w'])
-字符串中没有紧接字或'
字符的位置b(?<!')
-前面没有'
字符 的字边界位置w+
-一个或多个字字符。
参见Ruby演示:
sample_string = "let's could've they'll you're won't"
p sample_string.scan(/(?<![w'])w+/)
# => ["let", "could", "they", "you", "won"]