简体   繁体   English

正则表达式忽略一些字母

[英]Regexp ignores some letters

I'm trying to solve Chasing Subs problem . 我正在尝试解决Chasing Subs问题 I'm trying to generate that regex according to the input data. 我正在尝试根据输入数据生成该正则表达式。 The goal is go get all substrings (including overlapped ones) with all unique letters. 目的是获得所有带有唯一字母的子字符串(包括重叠的子字符串)。

I'm trying to use regexp like this: 我正在尝试像这样使用regexp:

regexp = /(?=(?<gs>.)(?<gu>[^\k<gs>])(?<gb>[^\k<gs>\k<gu>])(?<gm>[^\k<gs>\k<gu>\k<gb>])(?<ga>[^\k<gs>\k<gu>\k<gb>\k<gm>])(?<gr>[^\k<gs>\k<gu>\k<gb>\k<gm>\k<ga>])(?<gi>[^\k<gs>\k<gu>\k<gb>\k<gm>\k<ga>\k<gr>])(?<gn>[^\k<gs>\k<gu>\k<gb>\k<gm>\k<ga>\k<gr>\k<gi>])(?<ge>[^\k<gs>\k<gu>\k<gb>\k<gm>\k<ga>\k<gr>\k<gi>\k<gn>]))/
"archipelago".scan(regexp) #=> []
"archipelbgo".scan(regexp) #=> []
"brchipelbgo".scan(regexp) #=> []
"zrchipelzgo".scan(regexp) #=> [["z", "r", "c", "h", "i", "p", "e", "l", "z"]] 

Why does it behave like this? 为什么会这样呢? Why can't it find anything with "b" and "a" ? 为什么找不到带有"b""a" And why does it return only one (incorrect) result with "z" ? 又为什么它只返回一个带有"z" (不正确的)结果? What am I doing wrong? 我究竟做错了什么?

I don't think a regular expression is the correct tool for this problem. 我认为正则表达式不是解决此问题的正确工具。 We could do the following, however. 但是,我们可以执行以下操作。

def substrings(str)
  arr = str.chars
  (1..str.size).each_with_object([]) { |n,a|
    arr.each_cons(n) { |b| a << b.join if b == b.uniq } }
end

substrings("archipelago")
  #=> ["a", "r", "c", "h", "i", "p", "e", "l", "a", "g", "o", "ar", "rc", "ch", "hi",
  #    "ip", "pe", "el", "la", "ag", "go", "arc", "rch", "chi", "hip", "ipe", "pel",
  #    "ela", "lag", "ago", "arch", "rchi", "chip", "hipe", "ipel", "pela", "elag",
  #    "lago", "archi", "rchip", "chipe", "hipel", "ipela", "pelag", "elago", "archip",
  #    "rchipe", "chipel", "hipela", "ipelag", "pelago", "archipe", "rchipel", "chipela",
  #    "hipelag", "ipelago", "archipel", "rchipela", "chipelag", "hipelago", "rchipelag",
  #    "chipelago", "rchipelago"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM