Ruby Regex将/ abcdef / abcdef替换为/ abcdef

时间:2018-06-28 05:08:50

标签: ruby regex

通过比较变量str中的值来替换与变量路径的起始值不匹配的路由。

path = '/qqqq/rrrr'
str = %w|abcd efgh ijkl mnop \n|
path.gsub(/\w+/) { |rep| str.include?(rep) ? rep : 'unknown' }
  

输入>路径= / abcd输出> / abcd

     

输入>路径= / efgh输出> / efgh

     

输入>路径= / abcd / efgh输出> /未知

     

输入>路径= / xxxx输出> /未知

     

输入>路径= / xxxx / yyyy输出> /未知

     

输入>路径= / xxxx / abcd输出> /未知

正则表达式中是否包含等效项?

3 个答案:

答案 0 :(得分:1)

str = %w|abcd efgh ijkl mnop|
paths = %w|/abcd /efgh /abcd/efgh /xxxx /xxxx/yyyy /xxxx/abcd|
paths.map { |path| path[%r|\A/(?:#{Regexp.union(str)})/?\z|] || '/unknown' }
#⇒ ["/abcd", "/efgh", "/unknown", "/unknown", "/unknown", "/unknown"]

正则表达式为:\A表示字符串的开头,后跟一个斜杠,然后是一个正则表达式,该表达式以可能的并集形式构建,后面可能是单个斜杠,最后是字符串的末尾。 / p>

答案 1 :(得分:0)

使用gsub!应该做到这一点:

path.
  gsub(/\w+/) { |rep| str.include?(rep) ? rep : 'unknown' }.
  sub!("/unknown", "")

答案 2 :(得分:0)

如果任何与选项之一完全不匹配的路径都应转换:

private func updatePreviewLayer(layer: AVCaptureConnection, orientation: AVCaptureVideoOrientation) {

    layer.videoOrientation = orientation

    previewLayer.frame = self.view.bounds

}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let connection =  self.previewLayer?.connection  {

        let currentDevice: UIDevice = UIDevice.current

        let orientation = UIApplication.shared.statusBarOrientation

        let previewLayerConnection : AVCaptureConnection = connection

        if previewLayerConnection.isVideoOrientationSupported {

            switch (orientation) {
            case .portrait: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait)

                break

            case .landscapeRight: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeLeft)

                break

            case .landscapeLeft: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeRight)

                break

            case .portraitUpsideDown: updatePreviewLayer(layer: previewLayerConnection, orientation: .portraitUpsideDown)

                break

            default: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait)

                break
            }
        }
    }
}

但是您不需要正则表达式。