【问题标题】:Is possible to read collection of strings and return a Regexp?是否可以读取字符串集合并返回正则表达式?
【发布时间】:2016-07-16 06:43:29
【问题描述】:

我收集了来自多个来源的文件。

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

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]-

【问题讨论】:

标签: ruby regex pattern-matching pattern-mining


【解决方案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 等价物。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 2012-06-06
    • 2012-08-05
    • 1970-01-01
    • 2011-09-09
    • 2013-11-04
    • 1970-01-01
    相关资源
    最近更新 更多