简体   繁体   English

需要一些正则表达式的帮助(php)

[英]Need some help with regular expressions (php)

For example, I have the following code : 例如,我有以下代码:

$string  = "adf  gggg  eere value aaaa bbb (10) value 
ddttt ggg www (20) value ddttt ggg www dddd (40) ";
preg_match("/(value).*(\(\d+\))/is", $string, $result);
var_dump($result[2]); // outputs 40.

I'm trying to get the first value (10). 我想要获得第一个值(10)。 The code above outputs 40 which makes sense, but not what I want. 上面的代码输出40有意义,但不是我想要的。 The string pattern is : word "value", then a number of any characters, then "(", integer, ")". 字符串模式是:单词“value”,然后是多个任何字符,然后是“(”,整数,“)”。 It seems that I'm missing something obvious... I haven't worked too much with regular expressions, but I believe it can be solved somehow with ?<!value , no luck so far though. 似乎我错过了一些明显的东西...我没有用正则表达式做太多工作,但我相信它可以用某种方式解决?<!value ,但到目前为止没有运气。

Thanks for any help. 谢谢你的帮助。

.* is greedy, so it will match as many characters as possible, you want .*? .*是贪婪的,所以它会匹配尽可能多的字符,你想要的.*? which will match the minimum characters needed to complete the match: 这将匹配完成匹配所需的最小字符:

/(value).*?(\(\d+\))/

What's wrong with your regex is that .* is greedy, and tries to matchs as many letters as possible. 你的正则表达式有什么问题。*是贪婪的,并试图匹配尽可能多的字母。

preg_match("#value.*?\((\d+)\)#is", $string, $result);

But you can make it faster by using a negative class: 但是你可以通过使用负面类来加快速度:

preg_match("#value[^(]+\((\d+)\)#is", $string, $result);
.*?value.*?\((\d+)\).*

Being *? 存在 *? a reluctant match. 不情愿的比赛。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM