regex - squeeze spaces and remove dots in the names

Viewed 147

I'm working on cleaning up NAMES i.e remove the dots and spaces before the actual name starts. Example - Below is the test file

$ cat names.txt
J.J. Scott
J. S. Joyce
RV. Bradley Carter
M. N. K. Brailey
$

I need the output as below

JJ Scott
JS Joyce
RV Bradley Carter
MNK Brailey

The below perl attempt is not working for all scenarios.

perl -ne ' s/\.//g; s/ //; print ' names.txt
3 Answers

You may use this perl command that does it in singe substitution:

perl -pe 's/\.\h*(?=(?:[A-Z]\.)*\h+[A-Z])//g' file

JJ Scott
JS Joyce
RV Bradley Carter
MNK Brailey

RegEx Demo

RegEx Details:

  • \.\h*: Match a dot followed by 0 or more spaces or tabs
  • (?=(?:[A-Z]\.)*\h+[A-Z]): Lookahead to assert that we have 0 or more abbreviations followed by a space and an uppercase letter

You might use:

\G\p{Lu}+\K[.\h]+(?!\p{Lu}\p{Ll})
  • \G Assert the position at the end of the previous match, or at the start in this case
  • \p{Lu}+\K Match 1+ uppercase chars and forget what is matched so far using \K
  • [.\h]+ Match 1+ times either a dot or horizontal whitespace char
  • (?! Negative lookahead, assert what is directly to the right is not
    • \p{Lu}\p{Ll} Match an uppercase char followed by a lowercase char
  • ) Close lookahead

In the replacement use an empty string.

Regex demo

For example

perl -pe 's/\G\p{Lu}+\K[.\h]+(?!\p{Lu}\p{Ll})//g' names.txt

Output

JJ Scott
JS Joyce
RV Bradley Carter
MNK Brailey

You probably need a negative lookahead. The first regex removes dots. The second and third regexes are identical and both remove the space from space-separated capital (upper-case) letters unless the second is followed by a lower-case letter. The triple-initial name requires a repeat; otherwise, you end up with MN K Brailey. Using -p instead of -n avoids having to write print in the code.

perl -pe 's/\.//g; s/([A-Z]) ([A-Z])(?![a-z])/$1$2/g; s/([A-Z]) ([A-Z])(?![a-z])/$1$2/g' names.txt

Output:

JJ Scott
JS Joyce
RV Bradley Carter
MNK Brailey
Related