Regexp wanted to format string of letters
I want to format the initials of a persons name in a standard way. Every letter in the initials should be in uppercase and every letter (from to first until the last) must be followed by a dot. Like this:
JKP => J.K.P.
jk开发者_运维知识库p => J.K.P.
J.KP => J.K.P.
JK.P => J.K.P.
JKP. => J.K.P.
J.K.P => J.K.P.
etc...
Do you have a solution for me?
As we do not know which language you are using here's some pseudo code that should do the job:
replace all dots in the string with ''
split the string into a character array
join the character array with a '.' and make it uppercase
PHP equvalent:
$array = array (
'JKP',
'jkp',
'j.kp',
'jk.p',
'jkp.',
'j.k.p.',
);
foreach ($array as $s)
{
echo strtoupper (preg_replace ('/(\w)\W*/', '\1.', $s)), "\n";
}
Here is a Perl solution:
my @list = qw/JKP jkp J.KP JK.P JKP. J.K.P/;
for(@list){
s/\w(?!\.)/$&./g;
my $result = uc;
print "$result\n";
}
s/\w(?!\.)/$&./g
replaces all "word" chars not followed by a .
with that char and a .
, then just upper case it with uc
.
Here's a java solution: str.toUpperCase().replaceAll("(?<=\\w)(?!=\\.)", ".")
Decoded, (?<=\w)(?!=\.)
means match between characters where the previous character is a word character and the next character is not a dot
You should be able to adapt this regex to your language, whatever that is.
EDITED: To incorporate @Qtax suggestion.
精彩评论