develooper Front page | perl.beginners | Postings from April 2010

Re: Extract substring from offset to space or full stop

Thread Previous | Thread Next
From:
John W. Krahn
Date:
April 18, 2010 12:05
Subject:
Re: Extract substring from offset to space or full stop
Message ID:
4BCB57EA.9030409@shaw.ca
Mimi Cafe wrote:
> 
>> From: John W. Krahn [mailto:jwkrahn@shaw.ca] 
>> 
>> Mimi Cafe wrote:
>>> I used MySQL substr function to extra 100 characters from the result of a
>>> query, but understandably, I don't get what I want.
>>>
>>> Now I looked at Perl's substr function and it doesn't look like it can
>>> help me achieve what I need to.
>>>
>>> Let's say I have:
>>>
>>> $s = "The black cat climbed the green tree";
>>>
>>> How can I have this return the whole word climbed rather than the c (i.e.
>>> I need to get "The black cat climbed")? I need to get the remaining
>>> characters from the length till the next white space or end of a phrase.
>>>
>>> Any other way to overcome this limitation?  How can I use regex here?
>> 
>> $ perl -le'
>> my $s = "The black cat climbed the green tree";
>> my $length = length $s;
>> my ( $substring ) = $s =~ / \A ( .{15,$length}? \b ) /x;
>> print $substring;
>> '
>> The black cat climbed
> 
> It is a bit tricky. Just tried it and Perl warned:
> 
> The string is: The black cat is.
> Can't do {n,m} with n > m in regex; marked by <-- HERE in m/ \A ( .{19,18}
> <-- HERE ?\s+ \b ) / at substr.pl line 10.
> 
> My strings are not fixed length, but I do they are normally longer that the
> offset I used, so I should be fine I think.

$ perl -le'
my $s = "The black cat climbed the green tree";
my $end = length $s;
my $start = $end < 15 ? $end : 15;
my ( $substring ) = $s =~ / \A ( .{$start,$end}? \b ) /x;
print $substring;
'
The black cat climbed




John
-- 
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About