0

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.

4
  • How about using split? Commented Mar 21, 2014 at 15:51
  • 1
    Have you looked at the docs for split in Perl? The function is literally named split. perldoc.perl.org/functions/split.html Commented Mar 21, 2014 at 15:51
  • I tried using split but its giving some errors all the time, may be the code is not correct. Split works well for ',' or '.' but for string i am not able to use it. Commented Mar 21, 2014 at 15:53
  • Can you post the rest of your code then? What have you tried so far? Commented Mar 21, 2014 at 15:53

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Not sure i am using this properly or not, but the result is the same after using this as well... I tried several times but couldnt figure it out.
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.