php - 如何使用正则表达式获取数字后的字符

标签 php regex

假设我有以下行:

1309270927C1642,61N654NONREF

现在我想得到CD在第一个数字之后。现在这里有一些规则

  1. 前 6 位数字始终存在
  2. 后面的 4 位数字是可选的
  3. 之后你就有了 DC .

现在我想通过回顾来解决这个问题:

/(?<=\d{6,10})D|C/但这在 PHP 中是不允许的。

所以我尝试了一个非捕获组 /(?:\d{6,10})D|C/ 。但这捕获了1309270927C而不仅仅是C .

所以我的问题是如何捕获 DC

最佳答案

我会使用capturing subpattern ,像这样:

$string = "1309270927C1642,61N654NONREF";
$pattern = '/\d{6,10}(C|D)/';
preg_match($pattern, $string, $matches);
// $matches[1] contains the contents of the first subpattern
echo $matches[1];

关于php - 如何使用正则表达式获取数字后的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29514894/

相关文章:

php - mysql "boolean given"没有 mysql 错误

java - Spring @RequestMapping "Not Contains"正则表达式

regex - 如何在Matlab/Octave中使用regexp(正则表达式)来查找重叠匹配

C# 正则表达式匹配 15 个字符、单个空格、字母数字

grep 的 r 掩码用于查找重复的单词

php - 在mysql日期选择中指定小时数

php - 将 JS 和 CSS 包含到 magento 布局中的选定页面

javascript - 使用json显示图像

java - 带有服务器端 php 的 Android 文件 uploader

regex - 如何 grep 查找所有非 ASCII 字符?