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

Re: String manipulation

by citromatik (Curate)
on Jun 24, 2009 at 10:08 UTC ( #774325=note: print w/replies, xml ) Need Help??

in reply to String manipulation

Something like this may do the job:

use strict; use warnings; use feature qw/ :5.10 /; my @str = ("j k l foobar", "foobar", "jkl foobar", "1 2 3", + "jk l foobar", "foobar j k l", "foobar j kl", " ", " ", "j + jk foobar", "j k jk foobar", "j k l"); my $rx = qr/^((?:\w(?:\s+|\z))*)(.*)/; for my $str (@str){ my ($i,$s) = $str =~ /$rx/; $i =~ s/\s+//g; say $i ? join " ",$i,$s : $s; }


jkl foobar foobar jkl foobar 123 jk l foobar foobar j k l foobar j kl j jk foobar jk jk foobar jkl


Replies are listed 'Best First'.
Re^2: String manipulation
by abhy (Novice) on Jun 24, 2009 at 10:42 UTC
    If I am not asking for too much, can you please expand the regex with comments?


      my $rx = qr/ ^ # At the beginning of the string ( # Capture in $1 (?: # Paren for grouping (don't capture in $2) \w # match a "wordy" character (?: # paren for grouping, \s+|\z # match at least one space or the end of the + string ) )* # zero or more times ) # end of capture $1 (.*) # and match what comes after storing it in $ +2 /x # allow these comments ;

      The rationale is to match at the beginning all the one-character strings, storing them in $1. The rest of the input will be catched in $2


      If you don't know about YAPE::Regex::Explain, it is worth a look. I don't think it has been updated to take into consideration the new regex doodads in Perl 5.10 but it should be helpful regardless.

      Cheers - L~R

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2023-09-25 22:00 GMT
Find Nodes?
    Voting Booth?

    No recent polls found