正则表达式PHP在一定数量的#字符之后查找数字


Regular Expression PHP finding the number after a certain number of # characters

假设我有以下行:

09:00 23/02/2012#3.5#2.2#91#3.7#7.4#170#S#1033.1#(+1 Hpa / 3H).#0#3H##4.5#Plus de 2500m #6####00#### Brume.#

我想找到第15个字符之后的第一个数字或字符#
在本例中,我要查找的数字是6。

在这个例子中:

03:00 24/02/2012#8.9#5.5#79#3.7#5.55#190#S#1031.3#(-1.1 Hpa / 3H).#0#3H##10#300 et 600m#7####00#####

我要找的数字是7。

但它并不总是一个数字,例如在这一行:

00:00 29/02/2012#3.3#-0.2#78##3.7##N#1023.6#(+0.3 Hpa / 3H).#0#3H##22#Plus de 2500m######### Le ciel est clair.#

第15个#后面的字符也是#。

那么我怎么能得到这个数字或字符使用PHP正则表达式?

I tried

$content = '09:00 23/02/2012#3.5#2.2#91#3.7#7.4#170#S#1033.1#(+1 Hpa / 3H).#0#3H##4.5#Plus de 2500m #6####00#### Brume.#';
$iparr = preg_split ("/#/", $content); 
echo $iparr[16];

但是对于第三个例子,它什么也没有给出。(因为两个连续的#)

您可以使用explode

$parts = explode('#', $string, 16);
$item = substr($parts[15], 0, 1);

而在PHP>= 5.4.0中,你可以这样写:

$string = '09:00 23/02/2012#3.5#2.2#91#3.7#7.4#170#S#1033.1#(+1 Hpa / 3H).#0#3H##4.5#Plus de 2500m #6####00#### Brume.#';
$index  =  16;
var_dump(explode('#', $string)[$index - 1]);

下面是使用regex/preg_match的版本

<?php
$str = "00:00 29/02/2012#3.3#-0.2#78##3.7##N#1023.6#(+0.3 Hpa / 3H).#0#3H##22#Plus de 2500m######### Le ciel est clair.#";
$match = array();
# match until 15 '#', grab the digit as well as a character
preg_match( "/(.*?#){15}([^'d]*('d)|(.))/", $str, $match );
# the last element is the one containing best match, so just pop it
$char_after_15 = array_pop( $match );
print( $char_after_15 );

似乎有两个基本问题:(1)如何在给定字符之间可以有其他字符的情况下匹配特定数量的字符,以及(2)如何检索后面的内容而不检索所有内容。Silkfire的答案可能是你最好的选择,但这里是你如何用一个正则表达式来做到这一点:

if (preg_match('/^(?:[^#]*#){15}(.)/', $subject, $match)) {
    $result = $match[1];
}

如果你想一次将它应用于多个字符串,应该这样做:

preg_match_all('/^(?:[^#]*#){15}(.)/', $subject, $matches, PREG_PATTERN_ORDER);
$result = $matches[1];

$result在本例中是一个一维数组,其中包含了组#1在每个匹配中的内容。

EDIT:经过反思,看起来该字符串本质上是一个CSV记录,使用#而不是,作为分隔符,并且您希望从第16个字段获取数字。但数字是可选的,所以你取第15个分隔符后面的值如果它不是数字,你就把它当作空字段。如果是这种情况,您可能需要使用以下regex:

'/^(?:[^#]*#){15}('d*)/'

当没有数字时,它捕获一个空字符串,并且它将匹配一个超过一个数字的数字,如果重要的话。