"JR EWING") I am using this: $temp =~..." /> "JR EWING") I am using this: $temp =~..." /> "JR EWING") I am using this: $temp =~..."/>

Perl Regex: Merge multiple one-character substrings

128 views Asked by At

I have a string, and if there are two or more one-character units in it, I want to merge them ("J R EWING" --> "JR EWING")

I am using this:

$temp =~ s/\b(\w) (\w)\b/$1$2/g;

But it of course fails for "E T A HOFFMANN". Any thoughts?

2

There are 2 answers

0
ikegami On BEST ANSWER
s{\b((?:\w )+\w)\b}{ ( $1 =~ s/ //gr }eg;   # 5.14+

s{\b((?:\w )+\w)\b}{ ( my $s = $1 ) =~ s/ //g; $s }eg;

In this particular case, you could use a lookahead.

s/\b\w\K (?=\w\b)//g;   # 5.10+

s/(?<=\b\w) (?=\w\b)//g;
1
Casimir et Hippolyte On

You can use a lookahead, in this way the second letter is not a part of the match and the regex engine can continue the job:

$temp =~ s/\b\w\K (?=\w\b)//g;

\K discards all on the left from the whole match.