Apply Perl RegExp to Remove Parenthesis and Text at End of String

只谈情不闲聊 提交于 2021-02-04 21:38:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!