正则表达式为以特定字母结尾的n位数字

正则表达式为以特定字母结尾的n位数字

问题描述:

How can I extract:

  1. A string with n digits (say 10) that ends with a letter (say "A"), for example: 4024204455A
  2. A 12-digit number, for example: 192345006905

using a regex, from multiple text files with Go (golang)?

如何提取: p>

  1. 带有 以字母(例如“ A”)结尾的n位数字(例如10),例如:4024204455A li>
  2. 12位数字,例如:192345006905 li> ol >

    使用正则表达式从Go(golang)的多个文本文件中获取文本? p> div>

You could match either 12 digits [0-9]{12} or 10 digits and an uppercase character [0-9]{10}[A-Z] using an or | in a non capturing group (?: for example:

^(?:[0-9]{12}|[0-9]{10}[A-Z])$

Or match your values between word boundaries \b:

\b(?:[0-9]{12}|[0-9]{10}[A-Z])\b

To match one or more digits OR 10 digits followed by an uppercase character your could use this regex with word boundaries or anchored $^:

\b(?:[0-9]+|[0-9]{10}[A-Z])\b

<?php
$input = array();
$input[] = '123456789000A';
$input[] = '123456789012';
$input[] = '12345678901';

foreach($input as $i)
{
    preg_match("/^([0-9]+[a-z]{1}|[0-9]{12})$/i", $i, $m);
    print_r($m);
}

Output: First match, second match, third not match

Array
(
    [0] => 123456789000A
    [1] => 123456789000A
)
Array
(
    [0] => 123456789012
    [1] => 123456789012
)
Array
(
)