Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Regular Expression Search

by Riales (Hermit)
on Feb 09, 2012 at 19:05 UTC ( #952812=note: print w/ replies, xml ) Need Help??


in reply to Regular Expression Search

Others have already shown you a better way to go, but here's an implementation using index just for fun:

#!/usr/bin/perl use strict; use warnings; sub find_char { my ($char, $string) = @_; my @indexes_present = (); my $position = 0; while (length($string)) { my $index = index($string, $char); if ($index != -1) { $position = $position + ($index+1); push @indexes_present, $position; $string = substr($string, ($index+1), (length($string)-$in +dex)); } else { last; } } push @indexes_present, -1; my ($start_of_range, $end_of_range); my $previous_index; while (my $index = shift @indexes_present) { if (!defined($previous_index)) { $start_of_range = $end_of_range = $index; } elsif (($previous_index+1) == $index) { $end_of_range = $index; } else { if ($start_of_range == $end_of_range) { print "Found at $start_of_range\n"; } else { print "Found at $start_of_range to $end_of_range\n"; } $start_of_range = $end_of_range = $index; } $previous_index = $index; } } while (<DATA>) { print "\n$_"; find_char('-', $_); } __DATA__ A--B---C----D-E A-B--C---D----E ---------------

Prints:

A--B---C----D-E Found at 2 to 3 Found at 5 to 7 Found at 9 to 12 Found at 14 A-B--C---D----E Found at 2 Found at 4 to 5 Found at 7 to 9 Found at 11 to 14 --------------- Found at 1 to 15 Press ENTER or type command to continue

So yeah. The other way is better.


Comment on Re: Regular Expression Search
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (12)
As of 2014-09-02 12:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (22 votes), past polls