方括号中坐标[0:0:0]的正则表达式

时间:2014-10-13 14:12:14

标签: php regex

我试图让这个正则表达式模式起作用。我使用regex101测试它并在那里工作。但是,我的脚本无效。模式如下:

The radar detected one fleet from\[(\d{1,2}:\d{1,3}:\d{1})] is flying toward our Planet \[(\d{1,2}:\d{1,3}:\d{1})], arrival time left (\d{1,2}h\d{1,2}m\d{1,2}s). Enemy consist of: (.*)

示例文本如下:

  

雷达探测到[1:124:3]的一支舰队飞向我们的星球[10:1:6],到达时间为0h43m1s。敌人包括:小型货物(1),大型货物(1),轻型战斗机(1),重型战斗机(1),巡洋舰(1),战列舰(1),殖民船(1),回收船(1),间谍探测器(1),轰炸机(1),驱逐舰(1),无畏舰(1),死星(1)

正则表达式应捕获第一组坐标([ ])之间的数字,第二组坐标,到达时间,然后是Enemy Consist of:之后的所有内容。

我在脚本中使用的代码是

preg_match($regex,$text,$matches);

$regex是顶部的模式,$text与示例文本类似,但$matches未设置。

1 个答案:

答案 0 :(得分:2)

您的正则表达式按预期工作,问题是您的模式中缺少delimiters。您可能还想要转义点.以匹配文字。否则,它表示匹配除换行符之外的任何单个字符。

分隔符可以是任何非字母数字非反斜杠非空白字符

$text = 'The radar detected one fleet from[1:124:3] is flying toward our Planet [10:1:6], arrival time left 0h43m1s. Enemy consist of: Small Cargo(1), Large Cargo(1), Light Fighter(1), Heavy Fighter(1), Cruiser(1), Battleship(1), Colony Ship(1), Recycle Ship(1), Spy Probe(1), Bomber(1), Destroyer(1), Dreadnought(1), Death Star(1)';
$regex = '/The radar detected one fleet from\[(\d{1,2}:\d{1,3}:\d{1})] is flying toward our Planet \[(\d{1,2}:\d{1,3}:\d{1})], arrival time left (\d{1,2}h\d{1,2}m\d{1,2}s)\. Enemy consist of: (.*)/i';
preg_match($regex, $text, $matches);
var_dump($matches);

输出

array(5) {
  [0]=> string(322) "The radar detected one fleet from[1:124:3] is flying toward our Planet [10:1:6], arrival time left 0h43m1s. Enemy consist of: Small Cargo(1), Large Cargo(1), Light Fighter(1), Heavy Fighter(1), Cruiser(1), Battleship(1), Colony Ship(1), Recycle Ship(1), Spy Probe(1), Bomber(1), Destroyer(1), Dreadnought(1), Death Star(1)"
  [1]=> string(7) "1:124:3"
  [2]=> string(6) "10:1:6"
  [3]=> string(7) "0h43m1s"
  [4]=> string(196) "Small Cargo(1), Large Cargo(1), Light Fighter(1), Heavy Fighter(1), Cruiser(1), Battleship(1), Colony Ship(1), Recycle Ship(1), Spy Probe(1), Bomber(1), Destroyer(1), Dreadnought(1), Death Star(1)"
}