简体   繁体   中英

regex find numbers after capital letter php

I am trying to find all the numbers after a capital letter. See the example below:

E1S1 should give me an array containing: [1 , 1]

S123455D1223 should give me an array containing: [123455 , 1223]

i tried the following but didnt get any matches on any of the examples shown above :(

$loc = "E123S5";
$locs = array();
preg_match('/\[A-Z]([0-9])/', $loc, $locs);

any help is greatly appreciated i am a newbie to regex.

Your regex \\[AZ]([0-9]) matches a literal [ (as it is escaped), then AZ] as a char sequence (since the character class [...] is broken) and then matches and captures a single ASCII digit (with ([0-9]) ). Also, you are using a preg_match function that only returns 1 match, not all matches.

You might fix it with

preg_match_all('/[A-Z]([0-9]+)/', $loc, $locs);

The $locs\\[1\\] will contain the values you need .

Alternatively, you may use a [AZ]\\K[0-9]+ regex:

$loc = "E123S5";
$locs = array();
preg_match_all('/[A-Z]\K[0-9]+/', $loc, $locs);
print_r($locs[0]);

Result:

Array
(
    [0] => 123
    [1] => 5
)

See the online PHP demo .

Pattern details

  • [AZ] - an upper case ASCII letter (to support all Unicode ones, use \\p{Lu} and add u modifier)
  • \\K - a match reset operator discarding all text matched so far
  • [0-9]+ - any 1 or more (due to the + quanitifier ) digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM