问题
I have a string which includes parenthesis with text inside the parenthesis. How do I remove the parenthesis with text at the end of the string while keeping the other words in string?
Input:
Potatoes Rice (Meat)
Output:
Potatoes Rice
My code:
#! /usr/bin/perl
use v5.10.0;
use warnings;
my $noparenthesis = "Potatoes Rice (Meat)";
$noparenthesis =~ s/^/$1/gi;
say $noparenthesis;
回答1:
#! /usr/bin/perl
use v5.10.0;
use warnings;
my $noparenthesis = "Potatoes Rice (Meat)";
$noparenthesis =~ s/\(.*$//g;
say $noparenthesis;
If there are other words in parenthesis that you would like to keep since they are not in the end of the sentence then you can use the expression:
$noparenthesis =~ s/\s*\([^()]+\)\s*$//g;
This will only delete the parenthesis at the end of the string, and possible trailing spaces, as well as spaces preceding them (so no trailing spaces stay in the string). Since (
and )
characters are disallowed inside the matched parentheses, by the negated character class, this won't match nested parentheses, should the string have that.
来源:https://stackoverflow.com/questions/52246532/apply-perl-regexp-to-remove-parenthesis-and-text-at-end-of-string