2010-06-28 83 views
5

我想输入一个字符串并返回可用于描述字符串结构的正则表达式。正则表达式将用于查找更多与第一个相同结构的字符串。以编程方式从字符串派生正则表达式

这是故意模棱两可的,因为我肯定会错过SO社区中的某个人会抓到的案例。

请发布任何和所有可能的方式来做到这一点。

+4

人类甚至不能做到这一点那么好(只是看一些计算器上的可怕的正则表达式给出的问题),我们”我们应该善于检测模式。我怀疑这可以做,除非你有一个相当复杂的人工智能与大量的训练数据集。不过,只有一个输入字符串几乎没有任何用处。 – polygenelubricants 2010-06-28 19:42:18

+0

@polygenelubricants这个想法是使用这些模式来训练AI。 – smothers 2010-06-28 19:44:34

回答

12

琐碎的答案,可能不是你想要的是:返回输入字符串(与正则表达式特殊字符转义)。这总是一个匹配字符串的正则表达式。

如果您希望识别某些结构,您必须提供有关您希望识别的结构类型的更多信息。如果没有这些信息,问题就会以模糊的方式陈述出来,并且有许多可能的解决方案。例如,输入串 'ABA' 可被描述为

'ABA'

'ABA *'

“ABA?

'AB \ W'

'\瓦特{3}'

'()。B \ 1'

+8

更糟糕的是,输入“aba”可以简单地描述为“/.*/”,正如任何其他字符串一样。 – Chuck 2010-06-28 20:00:18

+0

@Chuck - 除了'“\ n”'。你可能意思是'/.*/ s'。 – Adrian 2010-06-28 21:38:35

+0

@Adrian:或者只是'//' – 2010-06-28 22:27:57

5

抱歉的此的长度。我将这个前提作为一个小小的挑战,并且在Ruby中提出了一个概念证明 。

我工作的假设是你可以提供一些应该匹配正则表达式(HITS)的字符串和一个不匹配的数字(MISSES)。

我基于遗传算法的天真执行的代码。请参阅底部的注释以了解我对这种方法的成功或其他方面的看法。

LOOP_COUNT = 100 

class Attempt 

    # let's try email 
    HITS = %w[[email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]] 
    MISSES = %w[[email protected] [email protected]@.com j.com @domain.com nochance [email protected] [email protected] username-at-domain-dot-com linux.org eff.org microsoft.com sjobs.apple.com www.apple.com] 

    # odd mixture of numbers and letters, designed to confuse 
    # HITS = %w[a123 a999 a600 a545 a100 b001 b847 a928 c203] 
    # MISSES = %w[abc def ghi jkl mno pqr stu vwx xyz h234 k987] 

    # consonants versus vowels 
    # HITS = %w[bcd cdb fgh ghf jkl klj mnp npm qrs srq tvw vwt xzb bzx] 
    # MISSES = %w[aei oyu oio euu uio ioe aee ooo] 

    # letters < 11 chars and no numbers 
    # HITS = %w[aaa aaaa abaa azaz monkey longstring stringlong] 
    # MISSES = %w[aa aa1 aa0 b9b 6zz longstringz m_m ff5 666 anotherlongstring] 

    MAX_SUCCESSES = HITS.size + MISSES.size 

    # Setup the various Regular Expression operators, etc.. 
    RELEMENTS = %w[. ? * + () \[ \] - |^$ \\ : @/{ }] 
    %w[A b B d D S s W w z Z].each do |chr| 
    RELEMENTS << "\\#{chr}" 
    end 
    %w[alnum alpha blank cntrl digit lower print punct space upper xdigit].each do |special| 
    RELEMENTS << "[:#{special}:]" 
    end 
    ('a'..'z').each do |chr| 
    RELEMENTS << chr 
    end 
    ('A'..'Z').each do |chr| 
    RELEMENTS << chr 
    end 
    (0..9).each do |chr| 
    RELEMENTS << chr.to_s 
    end 

    START_SIZE = 8 

    attr_accessor :operators, :successes 

    def initialize(ary = []) 
    @operators = ary 
    if ary.length < 1 
     START_SIZE.times do 
     @operators << random_op 
     end 
    end 
    @score = 0 
    @decay = 1 
    make_regexp 
    end 

    def make_regexp 
    begin 
     @regexp = Regexp.new(@operators.join("")) 
    rescue 
     # "INVALID Regexp" 
     @regexp = nil 
     @score = -1000 
    end 
    end 

    def random_op 
    RELEMENTS[rand(RELEMENTS.size)] 
    end 

    def decay 
    @decay -= 1 
    end 

    def test 
    @successes = 0 
    if @regexp 
     HITS.each do |hit| 
     result = (hit =~ @regexp) 
     if result != nil 
      reward 
     end 
     end 
     MISSES.each do |miss| 
     result = (miss =~ @regexp) 
     if result == nil 
      reward 
     end 
     end 
    end 
    @score = @successes 
    self 
    end 

    def reward 
    @successes += 1 
    end 

    def cross other 
    len = size 
    olen = other.size 
    split = rand(len) 
    ops = [] 
    @operators.length.times do |num| 
     if num < split 
     ops << @operators[num] 
     else 
     ops << other.operators[num + (olen - len)] 
     end 
    end 
    Attempt.new ops 
    end 

    # apply a random mutation, you don't have to use all of them 
    def mutate 
    send [:flip, :add_rand, :add_first, :add_last, :sub_rand, :sub_first, :sub_last, :swap][rand(8)] 
    make_regexp 
    self 
    end 

    ## mutate methods 
    def flip 
    @operators[rand(size)] = random_op 
    end 
    def add_rand 
    @operators.insert rand(size), random_op 
    end 
    def add_first 
    @operators.insert 0, random_op 
    end 
    def add_last 
    @operators << random_op 
    end 
    def sub_rand 
    @operators.delete_at rand(size) 
    end 
    def sub_first 
    @operators.delete_at 0 
    end 
    def sub_last 
    @operators.delete_at size 
    end 
    def swap 
    to = rand(size) 
    begin 
     from = rand(size) 
    end while to == from 
    @operators[to], @operators[from] = @operators[from], @operators[to] 
    end 

    def regexp_to_s 
    @operators.join("") 
    end 

    def <=> other 
    score <=> other.score 
    end 

    def size 
    @operators.length 
    end 

    def to_s 
    "#{regexp_to_s} #{score}" 
    end 

    def dup 
    Attempt.new @operators.dup 
    end 

    def score 
    if @score > 0 
     ret = case 
     when (size > START_SIZE * 2) 
     @score-20 
     when size > START_SIZE 
     @score-2 
     else 
     @score #+ START_SIZE - size 
     end 
     ret + @decay 
    else 
     @score + @decay 
    end 
    end 

    def == other 
    to_s == other.to_s 
    end 

    def stats 
    puts "Regexp #{@regexp.inspect}" 
    puts "Length #{@operators.length}" 
    puts "Successes #{@successes}/#{MAX_SUCCESSES}" 
    puts "HITS" 
    HITS.each do |hit| 
     result = (hit =~ @regexp) 
     if result == nil 
     puts "\tFAIL #{hit}" 
     else 
     puts "\tOK #{hit} #{result}" 
     end 
    end 
    puts "MISSES" 
    MISSES.each do |miss| 
     result = (miss =~ @regexp) 
     if result == nil 
      puts "\tOK #{miss}" 
     else 
      puts "\tFAIL #{miss} #{result}" 
     end 
    end 
    end 

end 

$stderr.reopen("/dev/null", "w") # turn off stderr to stop streams of bad rexexp messages 

# find some seed attempt values 
results = [] 
10000.times do 
    a = Attempt.new 
    a.test 
    if a.score > 0 
    # puts "#{a.regexp_to_s} #{a.score}" 
    results << a 
    end 
end 

results.sort!.reverse! 

puts "SEED ATTEMPTS" 
puts results[0..9] 

old_result = nil 

LOOP_COUNT.times do |i| 
    results = results[0..9] 
    results.map {|r| r.decay } 
    3.times do 
    new_results = results.map {|r| r.dup.mutate.test} 
    results.concat new_results 
    new_results = results.map {|r| r.cross(results[rand(10)]).test } 
    results.concat new_results 
    end 
    new_results = [] 
    20.times do 
    new_results << Attempt.new.test 
    end 
    results.concat new_results 
    results.sort!.reverse! 
    if old_result != results[0].score 
    old_result = results[0].score 
    end 
    puts "#{i} #{results[0]}" 
end 
puts "\n--------------------------------------------------" 
puts "Winner! #{results[0]}" 
puts "--------------------------------------------------\n" 
results[0].stats 

使用此代码学到的经验教训。总体而言,看起来多次运行较短的循环最有可能产生可用的结果。但是,这可能是由于我的实现,而不是遗传算法的性质。

您可能会得到可行的结果,但仍含有乱码的部分。

您将需要非常牢固掌握正则表达式,以了解有多少结果真正实现了他们所做的。

最终你的学习时间可能比尝试使用此代码作为快捷方式学习正则表达式要好得多。我意识到提问者可能没有这个动机,我尝试这个动机的原因是因为这是一个有趣的想法。

结果有很多折衷。你提供的HITS和MISSES越多样化,产生结果的时间越长,你需要运行的环路也越多。每一个都少一个可能会产生一个结果,这个结果要么是针对您提供的字符串的大量特定结果,要么是通用的,以至于在现实世界中无法使用。

我也硬编码了一些假设,比如标记时间过长的表达式。

+0

非常聪明。我想要一个能够生成正则表达式的工具来描述输入的差异,但从来没有比Confusion的第一个答案“返回字符串”更进一步。像你一样,我不确定这个工具是否真的值得,但读起来很有趣。 :) – sarnold 2011-10-04 22:11:27

0

进口刚刚发布了一个免费的工具,获得来自集例如字符串的正则表达式模式:“给它的数据的例子,你要拉出来,它会编程方式生成和测试正则表达式。”

https://regexpgen.import.io/

其免费的,但确实需要登录来使用它。

enter image description here

声明:我在import.io工作(这就是我如何知道存在)

0

site其实,您可以生成从示范文本正则表达式。你选择你想要的正则表达式的文本字符串的一部分,并用你选择的语言为你生成它。

看看它,它有一个例子,它的常见问题解释 - https://txt2re.com/index.php3?d=faq