PHP:preg_replace匹配某些数字但不匹配其他数字

时间:2012-04-24 22:09:13

标签: php regex

所以我一直在研究一个小项目,为游戏的脚本语言编写语法高亮显示器。这一切都顺利完成,除了一部分:数字。

以这些行为例

(5:42) Set database entry {healthpoints2} to the value 100.

(5:140) Move the user to position (29,40) on the map.

我想在最后突出显示100,而不是突出显示(5:42)或括号中的2。这些数字并不总是在同一个地方,并且不会总是只有一个数字。

我基本上需要一个正则表达式来说:

“匹配任何不在{}之间且与(#:#)模式不匹配的数字。”

我已经在这一天了一天半,我正在拔出我的头发试图解决它。对此的帮助将不胜感激! 我已经查看了regular-expressions.info,并尝试使用RegexBuddy,但我只是没有得到它:c

编辑:根据请求,这里还有一些直接从脚本编辑器复制的行。

(0:7) When somebody moves into position (**10** fhejwkfhwjekf **20**,

(0:20) When somebody rolls exactly **10** on **2** dice of **6** sides,

(0:31) When somebody says {...},

(3:3) within the diamond (**5**,**10**) - **20** //// **25**,

(3:14) in a line starting at (#, #) and going # more spaces northeast.

(5:10) play sound # to everyone who can see (#,#).

(5:14) move the user to (#,#) if there's nobody already there.

(5:272) set message ~msg to be the portion of message ~msg from position # to position #.

(5:302) take variable %var and add # to it.

(5:600) set database entry {...} about the user to #.

(5:601) set database entry {...} about the user named {...} to #.

2 个答案:

答案 0 :(得分:1)

当你看到这个解决方案时,你可能会踢自己......

假设这个所需的数字将始终用在一个句子中,它应该总是在它之前有一个空格。

$pattern = '/ [0-9]+/s';

如果前面的空格不总是存在,请告诉我,我会更新答案。


这是更新的正则表达式,以匹配您问题中的2个示例:

$pattern = '/[^:{}0-9]([0-9,]+)[^:{}0-9]/s';

第3次更新以解决您的问题修订:

$pattern = '/[^:{}0-9a-z#]([0-9]+[, ]?[0-9]*)[^:{}0-9a-z#]/s';

所以你不要强调像

这样的数字
  

{update 29 testing}

您可能需要预先剥去大括号,如下所示:

$pattern = '/[^:{}0-9a-z#]([0-9]+[, ]?[0-9]*)[^:{}0-9a-z#]/s';
$str = '(0:7) Hello {update 29 testing} 123 Rodger alpha charlie 99';
$tmp_str = preg_replace('/{[^}]+}/s', '', $str);
preg_match($pattern, $tmp_str, $matches);

答案 1 :(得分:0)

(\d+,\s?\d+)|(?<![\(\{:]|:\d)\d+(?![\)\}])

http://regexr.com?30omd

这会有用吗?