Jamal Mahroof
Jamal Mahroof

Reputation: 33

How to remove text within brackets in a string while still keeping the other text?

my $book = Spreadsheet::Read->new();
my $book = ReadData 
('D:\Profiles\jmahroof\Desktop\Scheduled_Build_Overview.xls');
my $cell = "CD7";
my $n = "1";
my $send = $book->[$n]{$cell};
$send =~ s/\(/ /g;
$send =~ s/\)//g;

I have the above code that gets data from an excel file and then picks out text from a specified cell and removes brackets from the string. I need to be able to remove everything within the brackets including the brackets themselves while leaving the rest of the text. The format of the string is exactly like the following : text(text)

Upvotes: 1

Views: 108

Answers (2)

user7818749
user7818749

Reputation:

$send =~ s/\(.*?\)//;

Explained:

s/ does the search \ escapes the bracket that comes next as it will be seen as part of the code if not escaped. (.*?\) here we say what we are searching for an we use non-greedy .*? to match anything up to the last bracket again the last bracket is escaped by \ / begins the replace function for the search / ends the search and replace.

So we Search for (*) and then replace with nothing.

Explaing Non greedy vs Greedy.

.* being greedy will match up until the last ) found

So if we have string((substring)end) then s/(.*)// will go from the first ( up to the last ) leaving you with string

non greedy will not, it will begin with the first ( up to the first ) leaving you with stringend) so it will be lazy and only match what you ask for which is from ( to ) where greedy will match grab everything, even if you have this (string)(())((strings))()()strings)strings)

Upvotes: 0

sidyll
sidyll

Reputation: 59277

If you don't have nested parentheses, this single substitution can do it:

$send =~ s/\(.*?\)//;

If these parenthesis are always the last item in text, it can be further simplified to:

$send =~s/\(.*//;

Upvotes: 0

Related Questions