将正则表达式插入另一个正则表达式 [英] Interpolating regexes into another regex

查看:58
本文介绍了将正则表达式插入另一个正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,k2k1 的差别很小.也就是说,k2 完全相同,只是它是使用插值定义的.(也就是说,我期望完全一样;从 p k2 的结果来看,显然不是.)

In the following code, k2 is minimally different from k1. That is, k2 is exactly the same except that it's defined using an interpolation. (That is, I expected it to be exactly the same; Obviously from the result of p k2 it is not.)

v  = /[aeiouAEIOUäöüÄÖÜ]/                 # vowels
k1 = /[[ßb-zB-Z]&&[^[aeiouAEIOUäöüÄÖÜ]]]/ # consonants defined without interpolation
k2 = /[[ßb-zB-Z]&&[^#{v}]]/               # consonants defined same way, but with interpolation

但如下所示,将 gsubk1 一起使用是有效的,而将它与 k2 一起使用时会以我不明白的方式失败.

But as below, using gsub with k1 works, whereas using it with k2 fails in a way I don't understand.

all_chars = "äöüÄÖÜß"<<('a'..'z').to_a.join<<('A'..'Z').to_a.join

p all_chars                  # "äöüÄÖÜßabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
p all_chars.gsub( k1 , '_' ) # "äöüÄÖÜ_a___e___i_____o_____u_____A___E___I_____O_____U_____"
p all_chars.gsub( k2 , '_' ) # "äöüÄÖÜ_abcdefghijklm_o_____u__x__ABCDEFGHIJKLMNOPQRSTUVWXYZ"
p k1                         # /[[ßb-zB-Z]&&[^[aeiouAEIOUäöüÄÖÜ]]]/
p k2                         # /[[ßb-zB-Z]&&[^(?-mix:[aeiouAEIOUäöüÄÖÜ])]]/

为什么不起作用?什么是(?-mix:...)?有没有办法让这项工作如我所愿?

Why doesn't it work? What is (?-mix:...)? Is there a way to make this work the way I was expecting it to?

推荐答案

我会这样做:

keywords = %w[foo bar]
regex = /\b(?:#{ Regexp.union(keywords).source })\b/i
# => /\b(?:foo|bar)\b/i

当您想一次测试单个字符串中是否出现多个子字符串时,这很有用.

That's useful when you want to test for the occurrence of multiple sub-strings inside a single string at once.

将正则表达式插入字符串不一定正确.默认情况下,当您这样做时,Ruby 使用 to_s 转换模式,这不是我想要的,因为我不想要模式、标志和所有内容的完整字符串表示.使用 source 返回什么我要:

Interpolating a regex into a string won't necessarily work right. By default, when you do that, Ruby converts the pattern using to_s, which is not what I want, because I don't want the full string representation of the pattern, flags and all. Using source returns what I want:

regex = Regexp.union(keywords)
regex         # => /foo|bar/
regex.inspect # => "/foo|bar/"
regex.to_s    # => "(?-mix:foo|bar)"
regex.source  # => "foo|bar"

这篇关于将正则表达式插入另一个正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆