简体   繁体   中英

Step by step of trimming white-space

I'm new to both perl and using regex. I need to remove the white space from a string.

I found an example but its pretty opaque to me. Is this an accurate description of whats happening?

sub trim($)
{
  my $string = shift;
  $string =~ s/^\s+//;
  # =~         : regex on variable string
  # s/         : replace match with value
  # ^\s+       : one or more white space characters at beginning
  # //         : no characters

  $string =~ s/\s+$//;
  #  =~        : regex on variable $string
  # s/         : replace match with value
  # \s+$       : one or more white space characters until end of line
  # //         : no characters
  return $string;
}

Yes it is.

Nothing else to say, actually.

Yes it is, as answered by sidyll . All your comments are accurate. Since these are basics you are asking, I would like to add a little.

You can do both in one expression, s/^\\s+|\\s+$//g (there are slight efficiency considerations). Note that now you need /g ("global") modifier so that all \\s+ are found. Otherwise the engine stops after it finds ^\\s+ (if there are any) and you are left with trailing space (if any).

You can use spaces in your regex, for readability, by using /x modifier. In this case it isn't much but with more complex ones it can help a lot.

$string =~ s% ^\s+ | \s+$ %%gx;

You may use different delimiters -- as long as you don't use that inside the regex. I use % above to avoid the editor coloring everything red (I find % not very readable in fact, but I need | inside). This is sometimes very useful, for example when your regex has a lot of / . Then you can use a different delimiter so you don't have to escape them.


Complete resources are given by ThisSuitIsBlackNot in the comment.

I've seen people praise this a lot: regex Demo , where you can type in a regex and see how it works.

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