SystemFun
SystemFun

Reputation: 1072

split() but keep delimiter

 my $string1 = "Hi. My name is Vlad. It is snowy outside.";

 my @array = split('.' $string1); ##essentially I want this, but I want the period to be kept

I want to split this string at the ., but I want to keep the period. How can this be accomplished?

Upvotes: 18

Views: 11005

Answers (2)

Barmar
Barmar

Reputation: 780808

You can use lookbehind to do this:

split(/(?<=\.)/, $string)

The regex matches an empty string that follows a period.

If you want to remove the whitespace between the sentences at the same time, you can change it to:

split(/(?<=\.)\s*/, $string)

Positive and negative lookbehind is explained here

Upvotes: 29

Dane Hillard
Dane Hillard

Reputation: 900

If you don't mind the periods being split into their own elements in the array, you can use parentheses to tell split to keep them:

my @array = split(/(\.)/, $string);

Upvotes: 13

Related Questions