我想解析一个字符串以查找在(character, n)
集中找到的前 N 个重复字符。
"ozzllluu"
和集合("u" => 2(、("d" => 2(、("l" => 3( 和 ("r" => 3(...我想找到"lll",因为它是 3 个字符并且发生在两个"u"之前。
程序式解决方案:
Rebol []
seq-set: [#"u" 2 #"d" 2 #"l" 3 #"r" 3]
str: "ozzllluu"
lastchar: ""
cnt: 1
seq-char: ""
foreach char str [
either char = lastchar [
cnt: cnt + 1
if (select seq-set char) = cnt [
seq-char: char
break
]
][
cnt: 1
]
lastchar: char
]
either seq-char = "" [
print "no seq-char"
][
print join "seq-char " seq-char
]
我将如何使用parse
规则执行相同的操作?
总之:
-
parse
在 (字符 ,n( 集中找到的前 n 个重复字符的字符串 - "功能"现有过程代码
- 狗粮变成雷波尔/红!
这是一个使用 Red's Parse 的解决方案(也适用于 R3(:
seq-set: [2 #"u" | 2 #"d" | 3 #"l" | 3 #"r"]
rule: [any [set char seq-set break | skip]]
red>> parse "ozzllluu" rule
red>> char
== #"l"
只是一个简单的规则作为起点
keys: ["uu" | "dd" | "lll" | "rrr"]
rule: [(k: none) any [[copy k keys to end ] | skip] ]
>> parse "olllddsslll rr rrr" rule k
== "lll"
下面的parse
规则会查找所有重复项并跳过其他重复项。
;Rebol 2 version
char: charset [#"a" - #"z"]
parse/all "wqooossssccfgg" [some [
copy x char [copy y some x (print [s: join x y length? s])]
| skip
]
]
;output
ooo 3
ssss 4
cc 2
gg 2
;Red version
parse "wqooossssccfgg" [some [
copy x char [copy y some x (print [s: append x y length? s])]
| skip ]]