是否可以读取字符串集合并返回Regexp?

时间:2016-03-28 22:00:38

标签: ruby regex pattern-matching pattern-mining

我有来自多个来源的文件集合。

每个文件都包含如下字符串:

File 1: A) B) C) D) E) 
File 2: a) b) c) d) e)
File 3: a. b. c. d. e.
File 4: a- b- c- d- e-
(...)

我知道我可以预先编码所有可能的模式,但我宁愿自动编写。

是否可以制作程序来读取文件并模式? 例如:

File 1: A) B) C) D) E) # => [ABCDE]\)
File 2: a) b) c) d) e) # => [abcde]\)
File 3: a. b. c. d. e. # => [abcde]\.
File 4: a- b- c- d- e- # => [abcde]-

1 个答案:

答案 0 :(得分:1)

Regexp.union足够聪明,可以逃脱这些问题,但就是这样。

str = "A) B) C) D) E)"
p re = Regexp.union(*str.split) # => /A\)|B\)|C\)|D\)|E\)/

Perl的Regexp::assemble也许可以做到这一点,AFAIK没有Ruby等价物。