Yetimwork Beyene
Yetimwork Beyene

Reputation: 249

How to get a sub portion of a string using perl?

Here's the string I'm using and the display of this string can be rearrange in any other and in my case, I'm only interested in getting the first parenthesis text and putting the remaining text on its on line..

For example,

(test network) or test(section memory) or test(section storage)

Ideal output:

test section network
or test(section memory) or test(section storage)

Here's the perl code I attempt to use to accomplish this goal.

    while(<readline>)
    {
        $_ =~ s/^\(test (.*)\)(.*)/test section $1\n$2/gi;
    }

The output does not match the ideal output I'm looking for.

Upvotes: 0

Views: 93

Answers (3)

arnaudbey
arnaudbey

Reputation: 890

perreal answer seems good, but here is another solution using ungreedyness (using ? after the *)

s/^\(test (.*?)\)\s*(.*)/test section $1\n$2/gi

Upvotes: 2

dethorpe
dethorpe

Reputation: 521

your expression is being too greedy, the first bit (test (.*)) matches up the the last ) on the line, so dosn't work.

Make the expression non-greedy

s/^\(test (.*?)\)(.*)/test section $1\n$2/gi

probably don't need the g (global) modifier either.

Upvotes: 1

perreal
perreal

Reputation: 97948

Try this:

s/^\(test ([^)]*)\)\s*(.*)/test section $1\n$2/gi

Upvotes: 1

Related Questions