如何在Ruby中找到第一次出现的正则表达式?

时间:2017-04-27 21:16:12

标签: ruby regex string

我使用的是Ruby 2.4。有没有更快的方法来找到第一次出现的正则表达式的字符串索引?我有这个

        first_occurrence = s.enum_for(:scan, regex).map { Regexp.last_match.begin(0) }.first

但是因为我收集所有职位然后只拿第一个职位似乎效率低下。

2 个答案:

答案 0 :(得分:1)

您可以使用

var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];


function lookUpProfile(firstName, prop){
   for(var i=0;i<contacts.length;i++){
       if((contacts[i].firstName===firstName)&&
         (contacts[i].hasOwnProperty(prop)===true)){
             return contacts[i][prop];
       }else if(contacts[i].hasOwnProperty(prop)===false){
          return "No such property" ;
       } 
   }
       return "No such contact" ;
}

lookUpProfile("Akira", "likes");

如果结果不是first_occurrence = s =~ /regex/ ,则它包含第一个匹配的索引。请参阅AWS Documentation - AmazonS3Client

请参阅Ruby demo

  

nil是Ruby的基本模式匹配运算符。 ... 如果找到匹配项,则运算符返回字符串中第一个匹配项的索引,否则返回=~

答案 1 :(得分:0)

我更喜欢的一个是通过方括号表达式访问找到的匹配项或nil

"trololol"[/lo/]
=> "lo"

"trololol"[/rofl/]
=> nil

此功能记录在Ruby docs