主帖
7 条回复
正则表达式嵌套该如何匹配?以及更多
我今天开始在StackOverflow的Careers上尝试应聘一些Remote的工作,遇到一道笔试题。
Code a simple Random Sentence Spinning Function(s) Or Class.
Basically you take this following variable Where the | is a delimiter
meaning either word could be shown up:
$rand_sentence = "{Please|Just} make this {cool|awesome|random} test sentence
{rotate {quickly|fast} and random|spin and be random}";
and the end result should be an output of the sentence like:
Please make this cool test sentence rotate fast and random.
OR
Just make this random test sentence spin and be random.
or any other random variation...
然后我就搜索了下“正则表达式嵌套该如何匹配”,找到了一个解决方案,$patten = '/{(?:[^{}]+|(?R))*}/';,然后写了一个程序。
<?php
$rand_sentence = "{Please|Just} make this {cool|awesome|random} test sentence
{rotate {quickly|fast} and random|spin and be random}";
$patten = '/{(?:[^{}]+|(?R))*}/';
echo randspin($rand_sentence);
function randspin($sentence) {
global $patten;
return preg_replace_callback($patten, "randpick",$sentence);
}
function randpick($input) {
global $patten;
$line = $input[0];
$line = substr($line,1,strlen($line)-2);
$matchCount = preg_match_all($patten,$line,$matches);
if($matchCount>0) {
return randspin($line);
}else {
$parts = explode("|",$line);
$index = rand(0,count($parts));
return $parts[$index];
}
}
代码提交以后,我才发现我的解有点问题,可以匹配简单的{Please|Just}问题以及{rotate {quickly|fast} and be random}问题,但是random|spin这样的外面没有{和}的解决不了,而按照题目的要求其实也是要能解决的。
大家看该如何解决?我尝试了几个写法都不对。