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?
Summary: To split a string and keep the delimiters/separators you can use one of the following methods: Use a regex module and the split() method along with \W special character. Use a regex module and the split() method along with a negative character set [^a-zA-Z0-9] .
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
split() method accepts two arguments. The first optional argument is separator , which specifies what kind of separator to use for splitting the string. If this argument is not provided, the default value is any whitespace, meaning the string will split whenever .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With