获取名字并删除字符串中的其余部分

Fetching the first name and deleting the rest in a string

我正在抓取网站的几个名称,我只需要那里的名字。 如何删除字符串中的所有内容并只输出名字:Veronica

这个我是知道的,记得是其他名字。

name = "Name: Veronica Ljunglöf"
name.gsub!("Name: ", '')

如果格式看起来一致,你可以这样做:

name = "Name: Veronica Ljunglöf"
=> "Name: Veronica Ljunglöf"
name.split[1]
=> "Veronica"

你可以做到...

name.gsub("Name: ", "").split.first

这是一个更冗长但也更通用的替代方法。您可以匹配多个模式,并可以使其适应名字和姓氏(例如)。

"Name: Veronica Ljunglöf".match(/Name: (\w*) \w*/)  #=> #<MatchData "Name: Veronica Ljunglöf" 1:"Veronica"> 

使用 MatchData#captures

访问 "Veronica"
"Name: Veronica Ljunglöf".match(/Name: (\w*) \w*/).captures #=> ["Veronica"] 

进行第一次(也是唯一一次)捕获

"Name: Veronica Ljunglöf".match(/Name: (\w*) \w*/).captures.first #=> "Veronica"

我会使用正则表达式:

r = /
    :\s+         # match a colon followed by one or more spaces
    \K           # forget everything matched so far
    [[:alpha:]]+ # match one or more letters
    /x           # extended/free-spacing regex definition mode

'name = "Name: Veronica Lodge"'[r]
  #=> "Veronica"<sup>1</sup>

That's the one Archie is looking at.