Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

finding offset within text for a given pattern

Status
Not open for further replies.

uprichard

Programmer
May 2, 2002
16
I have a large string (upto 900,000 characters). I need to search it for a given pattern i.e. "The dog sat on the mat" and then work with each part of the string. The string search string can appear in multiple places and I will need to get each sub section of the string.

I thought of using split, but that will not return the string that was searched as part of the returned values. I guess I could add it back by hand.

Is there a better way than using split? Is there a way to return the offset within the string that the pattern starts or ends at?

thanks,
 
As chazoid suggests, you could use index if you're searching for a particular string (as in the example you've given), rather than a pattern.

You can use split in the way you want if you put parens in your regexp. e.g.:
Code:
my $line = 'Did you hear? The dog sat on the mat and fell asleep.';

my @pieces = split /(The dog sat on the mat)/, $line;

Now, the first element of your array is 'Did you hear? ', the second is 'The dog sat on the mat' and the third is ' and fell asleep.'.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top