如何解析文本以获得所有提及者?

How to parse the text to get all mentionees?

我想解析文本以从该文本中获取提及量数组:

class Mentionee
  attr_reader :id, :display_name

  def initialize(id:, display_name:)
    @id = id
    @display_name = display_name
  end

  def self.parse(text)
     # ???
  end
end

mentionees = Mentionee.parse('[1:John C.] [2: Smith X.] you are awesome!')
mentioneess[0].id            # => '1'
mentioneess[0].display_name  # => 'John C.'
mentioneess[1].id            # => '2'
mentioneess[1].display_name  # => 'Smith X.'

我想这对你有帮助。

> '[1:John C.] [2: Smith X.] you are awesome!'.scan(/(?<=\[)(\d+)(?=:\s*([^\]]+))/)
=> [["1", "John C."], ["2", "Smith X."]]

如果我理解你想要解析传递给方法的文本 parse

  def self.parse(text)
    text.scan(/\[(.*?):(.*?)\]/).map do |e|
      {id: e[0], display_name: e[1]}
    end
  end

将产生:

[
  {id: "1", display_name: "John C."},
  {id: "2", display_name: "Smith X."}
]

您将能够按照您描述的方式使用

mentionees = Mentionee.parse('[1:John C.] [2: Smith X.] you are awesome!')
mentioneess[0][:id]            # => 1
mentioneess[0][:display_name]  # => 'John C.'
mentioneess[1][:id]            # => 2
mentioneess[1][:display_name]  # => 'Smith X.'