drm16022 2018-03-26 11:38
浏览 14

REGEX来自一组值的前两个字符?

I have a set of starting 2 alphabets as:

$arr = ['AB', 'DC', 'LF']

Problem: I need to make a regex (in PHP and TypeSript) that passes only those strings which starts with above values.

Example:

Valid:

ABwerty45^&*jk
ABwerrtty
LF%$^erftgt5234

Invalid:

TABYR56H
ab7877
Abtyu7

Any help is appreciated.

  • 写回答

2条回答 默认 最新

  • dongxiandi8313 2018-03-26 11:47
    关注

    You could join() the array and compose a regex with an alternation like this:

    <?php
    
    $strings = <<<DATA
    ABwerty45^&*jk
    ABwerrtty
    LF%$^erftgt5234
    
    TABYR56H
    ab7877
    Abtyu7
    DATA;
    
    $arr = ['AB', 'DC', 'LF'];
    $regex = '~^(?:' . join('|', $arr) . ').*~m';
    
    if (preg_match_all($regex, $strings, $matches)) {
        print_r($matches);
    }
    ?>
    


    Which yields
    Array
    (
        [0] => Array
            (
                [0] => ABwerty45^&*jk
                [1] => ABwerrtty
                [2] => LF%$^erftgt5234
            )
    
    )
    


    Basically, this says:
    ^             # match the start of the string
    (?:AB|DC|LF)  # AB or DC or LF
    .*            # 0+ characters in that line
    
    评论

报告相同问题?

悬赏问题

  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置