Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: How to remove \n between two words but retain one space

by Your Mother (Archbishop)
on Nov 26, 2005 at 18:28 UTC ( [id://511938]=note: print w/replies, xml ) Need Help??


in reply to How to remove \n between two words but retain one space

Something like this will do it.

my $str = "George Best "; $str =~ s/(?<=[[:alpha:]])(?:\s\s+|[^\S ]+)(?=[[:alpha:]])/ /g; print "'$str'\n";

(update: took off the pointless "s" from the s///) That might be more complicated (someone else might have a better one?) that than you need but I think it's good and will also fix things like--

my $str = "George" . \n ."Best";

It will not fix leading and trailing spaces. Just spacing between alpha characters.

Replies are listed 'Best First'.
Re^2: How to remove \n between two words but retain one space
by JediWizard (Deacon) on Nov 27, 2005 at 04:01 UTC

    I believe that:

    s/(?<=[[:alpha:]])\s+(?=[[:alpha:]])/ /g;

    Will have the same effect as your posted expression. Although it will replace a single space character between two letters with a single space character (essentially a no-op), because it is a simpler pattern will actually take less time to execute. Below I am posting a simple benchmark I used to test this theory. If I have missed something please enlighten me.

    #!/usr/local/bin/perl -w use strict; use Benchmark; my(@tests) = <DATA>; timethese(400, {his => sub{ s/(?<=[[:alpha:]])(?:\s\s+|[^\S ]+)(?=[[:a +lpha:]])/ /g foreach(@tests); }, mine => sub{s/(?<=[[:alpha:]])\s+(?=[[:alpha:]])/ /g f +oreach(@tests); }}); __DATA__ A sting with weird A string without weird Another variety with more wierd Anotherthingwithnospaces something odd soemthing normal [me@mylinux]$ ./space.pl Benchmark: timing 400 iterations of his, mine... his: 0 wallclock secs ( 0.07 usr + 0.00 sys = 0.07 CPU) @ 57 +14.29/s (n=400) (warning: too few iterations for a reliable count) mine: 0 wallclock secs ( 0.03 usr + 0.00 sys = 0.03 CPU) @ 13 +333.33/s (n=400) (warning: too few iterations for a reliable count)

    They say that time changes things, but you actually have to change them yourself.

    —Andy Warhol

      You're right. I was trying to be overly correct I think in avoiding replacing " " with " "; it slows down the works considerably so it's not the way to go for this.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://511938]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-19 16:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found