Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split() but keep delimiter

Tags:

split

perl

 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?

like image 300
SystemFun Avatar asked Feb 16 '13 06:02

SystemFun


People also ask

How do you split a string but keep the delimiters?

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] .

What is the default delimiter in split ()?

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.

Can split () take two arguments?

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 .


1 Answers

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

like image 168
Barmar Avatar answered Oct 03 '22 05:10

Barmar