基于两个哈希的Ruby Regex过滤器

时间:2019-01-20 21:30:22

标签: ruby regex

我正在尝试为Logsatash构建过滤器。它必须在Ruby中。
筛选器采用json格式的元数据,并基于允许字段的另一个json,它从元数据中删除所有不匹配的字段。
过滤器的主线是进行评估。如果传递的元数据名称在允许的哈希键中,则其值应为true。 (如示例中所示,允许的散列的所有值均为true,没关系)。
在允许的哈希中,可以有一个由通配符 *表示的 glob ,在这种情况下,它可以匹配任何字符串。
例如"instrument.network.*"表示"instrument.network.one""instrument.network.abc"可以通过。
但是,如果没有*中的"event.type",则只能传递这样的确切字符串,但不能 "event.type.abc"。换句话说,*代表任意数量的字符,类似于正则表达式。
简化的代码如下:

# input data
metadata = {"event.type"=>"message", "instrument.network.one"=>false, "instrument.network.two"=>false, "other.meta"=>true}
@allowed = {"timestamp"=>true, "event.type"=>true, "network.labels.*"=>true}

metadata.each do |key, val|
  # evaluation to be worked out
  evaluation = (@allowed.has_key? key)
  puts "the #{key} is allowed?: #{evaluation}"
  # metadata clearence
  metadata.delete(key) if !evaluation
end
puts "metadata after clearence: #{metadata}"

此代码的当前输出为:

the event.type is allowed?: true
the instrument.network.one is allowed?: false
the instrument.network.two is allowed?: false
the other.meta is allowed?: false
metadata after clearence: {"event.type"=>"message"}

但是我需要使通配符从"network.labels.*"传递,以产生如下输出:

the event.type is allowed?: true
the instrument.network.one is allowed?: true
the instrument.network.two is allowed?: true
the other.meta is allowed?: false
metadata after clearence: {"event.type"=>"message", "instrument.network.one"=>false, "instrument.network.two"=>false}

我正在尝试使用Regexp.union(@allowed) =~ key,但无法使其工作。我正在尝试其他红宝石技巧,例如.find等,但没有预期的结果。有一些使用单个正则表达式的示例,可以在字符串数组中查找,但没有其他方法。
Ruby构建这种过滤器的方式是什么?

1 个答案:

答案 0 :(得分:2)

我假设import { createStore, combineReducers, compose, applyMiddleware } from "redux"; import { connectRouter, routerMiddleware } from "connected-react-router"; import { createBrowserHistory } from "history"; import thunk from "redux-thunk"; import user from "./modules/user"; import stores from "./modules/stores"; import info from "./modules/info"; export const history = createBrowserHistory(); const middlewares = [thunk, routerMiddleware(history)]; const reducer = combineReducers({ user, stores, info, router: connectRouter(history) }); export default function configureStore(preloadedState) { return createStore( reducer, preloadedState, compose( applyMiddleware( ...middlewares ) ) ); } 应该如下。如果最后一个键不是以“ instrument”开头。或“ .labels”存在时,通配符“ *”的用途尚不清楚。

@allowed