查找字符串中的常见模式,并根据模式

时间:2015-06-12 18:14:14

标签: ruby algorithm pattern-matching

如何从一组输入字符串中自动提取常用字符或公共字符串?是否有算法执行此操作?

我试图找出如何解析1000个输入字符串并根据最大匹配模式自动创建字符串组。

ruby​​中有一个库可以做到吗?

Sample Input

What is your name?
Who wrote this book?
Your name starts with ABC
Is this book good?
Why is your name so long?
Have you read this book?



Expected Output.

your name
——————
What is your name?
Your name starts with ABC
Why is your name so long?

this book
————
Who wrote this book?
Have you read this book?
Is this book good?

根据luqui的评论编辑澄清并修正错误。

  1. 案件并不重要。

1 个答案:

答案 0 :(得分:-1)

您可以使用核心Ruby库:

["your name", "book"].map do |substring|
  [substring, text.lines.map(&:downcase).select { |line| line[substring] }]
end.to_h

# => {
#      "your name" => ["What is your name?", "Your name starts with ABC", ...],
#      "book" => [...]
#    }