使用扫描方法+正则表达式将字符串分解为单词,如果单词有""字符,请删除此字符及其后的所有内容


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"]

相关内容

  • 没有找到相关文章

最新更新