Inserting number after alphanumeric group not followed by numeric group
I have a string that contains one or more alphanumerical codes (starting with a letter) separated with an underscore. Some codes are followed by an index number, which is also separated with an underscore.
I want to insert an index number (always 1) after each code that is not already followed by an index.
Here's some sample :
one => one_1
one_tw2_tre_for => one_1_tw2_1_tre_1_for_1
one_tw2_tre_23_for => one_1_tw2_1_tre_23_for_1
one_3_tw2_4_tre_45 => one_3_tw2_4_tre_45
I can do it with two calls to preg_replace :
// Add '_1' after each code
$s = preg_replace('/[A-Za-z][A-Za-z0-9]+/', 开发者_JAVA技巧'$0_1', $s);
// Remove '_1' when followed by index
$s = preg_replace('/_1_([0-9]+)/', '_$1', $s);
I'm wondering if there's a way two do it with only one preg_replace (I tried lookahead and lookbehind, without success) or a different way that might be faster, processor wise.
Thanks ! :-)
preg_replace('/[A-Za-z][A-Za-z0-9]+(?!_[0-9]|[A-Za-z0-9])/', '$0_1', $s);
Or, more concise:
preg_replace('/[A-Za-z][A-Za-z0-9]+(?=_|$)(?!_[0-9])/', '$0_1', $s);
精彩评论