duanjuelian4640 2018-01-25 08:31
浏览 264
已采纳

一个正则表达式,用于匹配单个字符,后跟数字,以“c”结尾

I need a regex for the following pattern:

a single character from [e-g] followed by one or more numbers that ends with character 'c'.

for example e123f654g933c expected result:

Array
(
    [0] => Array
        (
            [0] => e123
            [1] => f654
            [2] => g933
        )

)

or

e123f654g933ce99f77g66c expected result:

Array
(
    [0] => Array
        (
            [0] => e123
            [1] => f654
            [2] => g933
        ),
    [1] => Array
        (
            [0] => e99
            [1] => f77
            [2] => g66
        )

)

I tried using the following but I don't know what to do with 'c' part. I used this ([e-g]{1}[0-9]{1,}c)+ but it fails.

$subject="e123f654g933ce99f786g776c";
preg_match_all('/[e-g]{1}[0-9]{1,}/', $subject, $match);
print '<pre>' . print_r($match,1) . '</pre>';

Array
(
    [0] => Array
        (
            [0] => e123
            [1] => f654
            [2] => g933
            [3] => e99
            [4] => f786
            [5] => g776
        )

)

thanks.

  • 写回答

4条回答 默认 最新

  • dongzhiyan5693 2018-01-25 13:56
    关注

    I couldn't manage to generate your multi dimensional output array via a single regex function call.

    Code (Demo: https://3v4l.org/f5nnk )

    $strings=[
        'e123f654g933c',
        'e123f654g933ce99f77g66c'
    ];
    
    foreach($strings as $string){
        var_export(
            array_map(
                function($v){
                    return preg_match_all('/[e-g]\d+/',$v,$out2)?$out2[0]:[];  // split the groups by string format
                    // or return preg_split('/\d+\K/',$v,NULL,PREG_SPLIT_NO_EMPTY);
                    // or return preg_split('/(?=[e-g])/',$v,NULL,PREG_SPLIT_NO_EMPTY);
    
                },
                preg_match_all('/(?:[e-g]\d+)+(?=c)/',$string,$out1)?$out1[0]:[]  // split into groups using c
                // or explode('c',rtrim($string,'c'))
                // or array_slice(explode('c',$string),0,-1)
                // or preg_split('/c/',$string,NULL,PREG_SPLIT_NO_EMPTY)
            )
        );
        echo"
    
    ";
    }
    

    Output:

    array (
      0 => 
     array (
        0 => 'e123',
        1 => 'f654',
        2 => 'g933',
      ),
    )
    
    array (
      0 => 
      array (
        0 => 'e123',
        1 => 'f654',
        2 => 'g933',
      ),
      1 => 
      array (
        0 => 'e99',
        1 => 'f77',
        2 => 'g66',
      ),
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法