0

I have a RegExp

/h.*e.*l.*l.*o.*/i

And I have my paragraph that its being run on.

Hey look at that lion!

The result is this:

answer[0] = Hey look at that lion!
answer[1] = H
answer[2] = e
answer[3] = l
answer[4] = l
answer[5] = o

I was wondering if I could get a result like this:

answer[0] = Hey look at that lion!
answer[1] = Hello

by only changing my RegExp. Maybe using grouping or something? And if the answer to that question is no, then what are my other options? I really don't want to loop over the answer and string it together either, but if that's the only way then I will do it like that I suppose.

4

3 回答 3

1

你的表情很好。您只需执行一次并返回一个匹配项。没关系。

在这里查看参考:http ://regex101.com/r/jU3zU2

如果您愿意,您可以像我在示例中那样使用反向引用来获取整个数据。

但是,您想返回“你好”,这就是您在正则表达式中所拥有的......所以呃..什么?

于 2012-08-27T17:36:03.383 回答
0

使用正则表达式是不可能的。使用正则表达式时不可更改的规则之一是每个字符只能匹配一次。这意味着您不能返回整个句子其中的某些部分。

例子:

"abc".match(/a|b|c|(abc)/g)

最后一abc组,虽然它会匹配,但永远不会匹配,因为 abc 的字符匹配前面的表达式a|b|c

我不知道你想通过在正则表达式中对结果进行硬编码来实现什么,我假设你的真实代码应该做其他事情。如果没有,只需将“hello”分配给一个变量。

于 2012-08-27T18:12:28.923 回答
0
array_shift($answer);
$answer = implode('',$answer);

array_shift 将从结果数组中删除包含整个字符串的元素,然后 implode 会将它们全部组合成一个字符串。

于 2012-08-27T17:35:53.460 回答