3

Essentially, here's what I want to do:

if ($expression =~ /^\d{num}\w{num}$/)
{
     #doSomething
}

where num is not an identifier, but could stand for any integer greater than 0 (\d and \w were arbitrarily chosen). I want to match a string iff it contains two groups of related characters, one group immediately followed by the other, and the number of characters in each group is the same.

For this example, 123abc and 021202abcdef would match, but 43abc would not, neither would 12ab3c or 1234acbcde.

4

2 回答 2

6

不要认为字符串是从左到右增长的,而是从外到内:

xy
x(xy)y
xx(xy)yy

您的正则表达式将类似于:

/^(x(?1)?y)$/

where(?1)是对外部括号的引用。?使其成为可选的,以便为递归匹配提供某种“基本情况”。这可能是正则表达式如何用于匹配上下文无关文法的最简单示例——尽管使用解析器生成器或解析器组合器库通常更容易正确处理。

于 2013-06-11T19:32:34.883 回答
4

嗯,有

if ($expression =~ /^(\d+)([[:alpha:]]+)$/ && length($1)==length($2))
{
    #doSomething
}

正则表达式并不总是最好的选择。

于 2013-06-11T19:35:28.643 回答