'Can I save the split character of a string in Perl [duplicate]
I want to split a multi sentence paragraph into its constituent sentences whilst retaining the split characters ie the '. ? !'. The code I'm using is:
my @Sentence = split(/[\.\?\!]/,$Paragraph);
Is there any way that I can save those sentence terminators?
Solution 1:[1]
Yes, if you add parentheses around the delimiter, they will be included in the result list.
my @Sentence = split /([\.\?\!])/, $Paragraph;
E.g. if you have the string foo.bar.baz before you would get qw(foo bar baz), and with parentheses you would get qw(foo . bar . baz).
In case you want to keep the delimiters attached to the sentence, you could use a lookbehind assertion
my @Sentence = split /(?<=[\.\?\!])/, $Paragraph;
# result qw(foo. bar. baz)
If you want to strip unnecessary spaces after the match, you could use /(?<=[\.\?\!]) */.
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 |
