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

时间:2018-03-26 11:38:36

标签: php regex typescript

我有一组起始的2个字母:

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

问题:我需要制作一个正则表达式(在 PHP TypeSript ),它只传递以上述值开头的字符串。< / p>

示例:

有效:

ABwerty45^&*jk
ABwerrtty
LF%$^erftgt5234

无效:

TABYR56H
ab7877
Abtyu7

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

你可以join()数组并用这样的替换组成一个正则表达式:

<?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);
}
?>

<小时/> 产生

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

)

<小时/> 基本上,这说:

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

答案 1 :(得分:0)

您可以检查数组中是否存在前2个字符,而不是正则表达式:

$arr = ['AB', 'DC', 'LF'];
if (in_array(substr("ABwerty45^&*jk",0, 2), $arr)) {
    // ...
}

Demo

&#13;
&#13;
const strings = [
  "ABwerty45^&*jk",
  "ABwerrtty",
  "LF%$^erftgt5234",
  "TABYR56H",
  "ab7877",
  "Abtyu7"
];
const arr = ['AB', 'DC', 'LF'];

strings.forEach((s) => {
  let match = arr.includes(s.substring(0, 2));
  match ? console.log("Match : ", s) : console.log("No match: ", s);
});
&#13;
&#13;
&#13;