为了先说明一下,我会使用index
,substr
或类似的方法,因为它们是我特定情况下的明显解决方案,但我正在制作一个grammar
,所以我只能使用regex
。 :(
话虽如此,关于将Perl5 / PCRE正则表达式翻译为Perl6正则表达式的建议仍然是很好的SO内容,因为Perl 6越来越流行,它的正则表达式引擎非常不同。
这里有一个正则表达式,只匹配不包含给定字符列表中任何字符的字符串。
(在这里试一试.)
^(?:(?!\/).)*$
^ # assert position at start of string
(?: # begin a noncapturing group
(?! # negative lookahead: following regex must not match the string
\/ # literal forward slash
) # end negative lookahead
. # any character, once
)* # the previous noncapturing group, 0..Inf times
$ # assert position at end of string
显然,由于多种原因,在Perl 6中无法使用。
基于在perl6正则表达式文档中查找非捕获组
和负向先行断言
,我尝试将其翻译为以下内容:
[ \/ <!before .*> \/ <!after .*> || .? ]*
还有一个细节(我想是这个):
[ # begin a noncapturing group which apparently look like a charclass in p6
\/ # a literal forward slash
<!before .*> # negative lookahead for the immediately preceding regex (literal /)
\/ # a literal /
<!after .*> # negative lookbehind for the immediately preceding regex
|| .? # force this to be a noncapturing group, not a charclass
]* # end noncapturing group and allow it to match 0..Inf times
我像这样实现:
my regex not-in { ... }
,然后像这样使用:/^<not-in>$/
。但是它对于每个字符串都返回Nil
,这意味着它无法正常工作。我找不到Perl 6的http://regex101.com等效工具,因此与Perl 5一样轻松地玩耍并不容易。
如何将此转换为Perl 6?
Grammar::Tracer
和Grammar::Debugger
。在我调试语法时,它们非常有帮助。 - Christopher Bottoms"a" !~ m{/}
,在Perl 6中则为"a" !~~ m{'/'}
,效果会更好。虽然我可以想象出一些情况,您需要知道如何编写像您所拥有的那样的内容。但在这种特定情况下,m{^ [^\/]* $}x
会更好。 - Brad Gilbertm{^ [^\/]* $}x
仍然更好 - Brad Gilbert"a" !~~ m{'/'}
添加为答案。@cat 如果Brad Gilbert将其作为答案添加,那么它应该是被接受的答案。 - Christopher Bottoms