繁体   English   中英

如何基于数组中的预定义值拆分字符串

[英]How to split string based on pre-defined values from Array

我想基于一开始就定义为常量的数组拆分字符串:

class Query
  OPERATOR = [':','=','<','>','<=','>=']
  def initialize(params)
    #Here i want to split given params if it contains any
    #of the operators from OPERATOR     
  end
end

Query.new(["Status<=xyz","Org=abc"])

我怎样才能做到这一点?

OPERATOR = ['<=','=>',':','=','<','>']

r = /\s*#{ Regexp.union(OPERATOR) }\s*/
  #=> /\s*(?-mix:<=|=>|:|=|<|>)\s*/

str = "Now: is the =time for all <= to =>"

str.split(r)
  #=> ["Now", "is the", "time for all", "to"] 

请注意,我对OPERATOR的元素进行了重新排序,以使'<=''=>' (每个元素由数组中两个长度为1的字符串组成)位于开头。 如果不这样做,

OPERATOR = [':','=','<','>','<=','>=']
r = /\s*#{ Regexp.union(OPERATOR) }\s*/
  #=> /\s*(?-mix::|=|<|>|<=|>=)\s*/ 
str.split(r)
  #=> ["Now", "is the", "time for all", "", "to"] 

str.split(r)

参见Regexp :: union

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM