Match a string against multiple patterns

前端 未结 2 978
甜味超标
甜味超标 2020-12-01 02:14

How can I match a string against multiple patterns using regular expression in ruby.

I am trying to see if a string is included in an array of prefixes, This is not

相关标签:
2条回答
  • 2020-12-01 02:19

    If you can use a single string, it might be faster to write a regex containing the possible values.

    e.g.

    /(Mr\.|Mrs\.| ... )/.match(name)
    
    0 讨论(0)
  • 2020-12-01 02:35

    Use Regexp.union to combine them:

    union(pats_ary) → new_regexp

    Return a Regexp object that is the union of the given patterns, i.e., will match any of its parts.

    So this will do:

    re = Regexp.union(prefixes)
    

    then you use re as your regex:

    if name.match(re)
        #...
    
    0 讨论(0)
提交回复
热议问题