我试图使用Perl正则表达式捕获C风格代码块之前和之后的一些文本.到目前为止,这就是我所拥有的:
use strict;
use warnings;
my $text = << "END";
int max(int x, int y)
{
if (x > y)
{
return x;
}
else
{
return y;
}
}
// more stuff to capture
END
# Regex to match a code block
my $code_block = qr/(?&block)
(?(DEFINE)
(?<block>
\{ # Match opening brace
(?: # Start non-capturing group
[^{}]++ # Match non-brace characters without backtracking
| # or
(?&block) # Recursively match the last captured group
)* # Match …Run Code Online (Sandbox Code Playgroud) 这是这个问题的后续内容.
看看这个模式:
(o(?1)?o)
Run Code Online (Sandbox Code Playgroud)
它匹配任何o长度为2 n的序列,其中n≥1.
它可以工作,请参阅regex101.com(为了更好的演示添加了字边界).
问题是:为什么?
在下文中,字符串的描述(匹配与否)将只是粗体数字或粗体术语,描述长度,如2 n.
细分(添加空格):
( o (?1)? o )
( ) # Capture group 1
o o # Matches an o each at the start and the end of the group
# -> the pattern matches from the outside to the inside.
(?1)? # Again the regex of group 1, or nothing.
# -> Again one 'o' at the start and one at the end. …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个递归正则表达式来捕获代码块,但由于某种原因它似乎没有正确捕获它们.我希望下面的代码能够捕获函数的完整主体,但它只捕获第一个if语句的内容.
它几乎就像.+?是以某种方式吞噬了第一个{,但它应该是非贪婪的,所以我不明白它为什么会这样.
是什么导致它以这种方式行事?
脚本:
use strict;
use warnings;
my $text = << "END";
int max(int x, int y)
{
if (x > y)
{
return x;
}
else
{
return y;
}
}
END
# Regular expression to capture balanced "{}" groups
my $regex = qr/
\{ # Match opening brace
(?: # Start non-capturing group
[^{}]++ # Match non-brace characters without backtracking
| # or
(?R) # Recursively match the entire expression
)* …Run Code Online (Sandbox Code Playgroud) 我正在编写一个简单的正则表达式,需要接收一对坐标和/或地图名称。
例如:
move 10 15 # should returns [[10, 15]]
move 10 15 map # should returns [[10, 15, 'map']]
move map # should returns [['map']]
move 10 15 mapA mapB # should returns [[10, 15, 'mapA'], ['mapB']]
move 10 15 mapA mapB 33 44 # should returns [[10, 15, 'mapA'], ['mapB'], [33, 44]]
move 10 15 mapA 33 44 mapB # should returns [[10, 15, 'mapA'], [33, 44, 'mapB']]
Run Code Online (Sandbox Code Playgroud)
然后,我写了这个正则表达式:
/
(?(DEFINE)
(?<coord> (?<x>\d+)\s+(?<y>\d+) )
(?<map> (?<mapname>[a-zA-Z]+) )
(?<commands> …Run Code Online (Sandbox Code Playgroud)