Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Regular Expressions: Removing 'only' single spaces from a string

by ioannis (Abbot)
on Oct 20, 2005 at 22:59 UTC ( #501836=note: print w/replies, xml ) Need Help??


in reply to Regular Expressions: Removing 'only' single spaces from a string

The OP asked to remove single spaces, not whitespaces. He did not mention about word-boundaries either; and even if he did, we don't know if the language he is using is covered under the \b concept of Perl. And therefore, to obey the bounds of the original request, here is another solution using negative lookahead.
s/\ (?!\ )//gx ;
  • Comment on Re: Regular Expressions: Removing 'only' single spaces from a string
  • Download Code

Replies are listed 'Best First'.
Re^2: Regular Expressions: Removing 'only' single spaces from a string
by Roy Johnson (Monsignor) on Oct 20, 2005 at 23:15 UTC
    It will remove the last space from any run of spaces. That is why you need both lookahead and lookbehind to make it work properly.

    Caution: Contents may have been coded under pressure.
Re^2: Regular Expressions: Removing 'only' single spaces from a string
by BioBoy (Novice) on Oct 20, 2005 at 23:37 UTC
    This solution worked perfectly. Now, do you think you could break it down for me? Forgive me, but I'm having a little trouble understanding it.

      Did it though? Consider:

      use warnings; use strict; my $str1= "It is very very cold now\n"; my $str2 = $str1; $str1 =~ s/(?<! ) (?! )//g; print $str1; $str2 =~ s/ (?! )//g; print $str2;

      which prints:

      Itisvery verycoldnow Itisvery verycoldnow

      Which string is correct? The (?<! ) is a zero width look back negative assertion: it matches if there isn't a space before the current space being matched. The (?! ) is a zero width look ahead negative assertion: it matches if there isn't a space after the current space being matched. Together these ensure that only single spaces are matched: only match a space that doesn't have a space before it and doesn't have a space after it.

      You should have a look at perlretut.


      Perl is Huffman encoded by design.
        Thanks for that explaination.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2022-11-28 17:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?