2

I have a string which is of this form:

$str = "30M1I20M150N20M190N50M"

EDITED: I would like to split this string so that my ouput looks like this:

30M1I20M
150N
20M
190N
50M

However, when I tried with,

@split_str = split(/(\d+)N/, $str);

I get:

30M1I20M
150
20M
190
50M

As you can see, the N gets omitted in the result (150, 190 instead of 150N and 190N). Could anyone tell me how I should go about? Thank you!

2
  • 2
    Your example does not make sense: if you split on N keeping the N you get: 30M1I20M150N, 20M190N and 50M. Did I get something wrong? Commented Nov 27, 2011 at 14:14
  • 1
    You can as suggested in the answers put the N in the capture group or just reattach it to the strings Commented Nov 27, 2011 at 14:20

3 Answers 3

7

Put the N inside the capture group.

/(\d+N)/
Sign up to request clarification or add additional context in comments.

Comments

1

See Look-around assertions in perlre.

split /(?<=[NM])/, '30M1I20M150N20M190N50M'
# returns
# qw(
#     30M
#     1I20M
#     150N
#     20M
#     190N
#     50M
# )

2 Comments

I believe the '?<=' is a look ahead insertion? I never really understood those, what exactly it does? thanks
See Look-around assertions in perlre. But I'm repeating myself.
1

try the following (not tested):

split(/(\d+?[MN])/, $str);

1 Comment

Since I guess you are trying to get also 'M's

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.