Reputation: 69
I have a string like this
"Name : somedata,123 Name : somedata1,234 Name :somedata3,345"
I need to split the data to the next line where ever "Name "
occurs,
I need the final output like this :
Name :somedata,123
Name :somedata1,234
Name :somedata3,345
Please suggest. Thanks.
Upvotes: 0
Views: 104
Reputation: 35198
You can also solve this using split
and a positive lookahead assertion
:
$string = "Name : somedata,123 Name : somedata1,234 Name :somedata3,345";
my @strings = split /(?=Name)/, $string;
print "<$_>\n" for @strings;
Outputs:
<Name : somedata,123 >
<Name : somedata1,234 >
<Name :somedata3,345>
Note, if the pattern is of zero width, then split will not match at the beginning of a string. For this reason, we do not need the positive look behind assertion to ensure that we aren't at the start.
Also, if we wanted to get rid of the trailing spaces, we could do that in the split as well:
my @strings = split /\s*(?=Name)/, $string;
Upvotes: 1
Reputation: 241858
You can use substitution with a look-behind and look-ahead: if there is a position preceded by anything (i.e. not the very beginning) followed by Name
, you insert a newline:
my $string = "Name : somedata,123 Name : somedata1,234 Name :somedata3,345";
$string =~ s/(?<=.)(?=Name)/\n/g;
Upvotes: 4