'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?
Solution 1:[1]
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
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
| Solution 2 | Dane Hillard |
