简体   繁体   中英

Perl Regex: Merge multiple one-character substrings

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

I am using this:

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

But it of course fails for "ETA HOFFMANN". Any thoughts?

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;

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.

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