简体   繁体   English

用简单的正则表达式匹配字符串

[英]matching strings with simple regex

In a Rails app I need to identify certain URLs paths that are expressed in this form: 在Rails应用程序中,我需要标识以这种形式表示的某些URL路径:

paths = ['/a/*/b/c', '/f/*']

I'm in a middleware and I have access to the path, what kind of conditional should I write to check if the current URL path has a match with an entry in the provided array? 我在中间件中,并且可以访问该路径,应该编写哪种条件来检查当前URL路径是否与提供的数组中的条目匹配?

  path = Rack::Request.new(env).path
  included = paths.any? { |s| path.include?(s) }

this only checks for inclusion, but now wildcards have arrived. 这只会检查是否包含,但现在通配符已经到来。

You can convert paths into regular expression patterns: 您可以将路径转换为正则表达式模式:

paths = ['/a/*/b/c', '/f/*']

path = Rack::Request.new(env).path
patterns = paths.map { |path| Regexp.new path.gsub(/\*/, '[^/]+') }
    # Convert `*` to `[^/]+` to match any non-`/` characters. 
included = patterns.any? { |s| path =~ s }

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

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