应用 Perl RegExp 删除字符串末尾的括号和文本 [英] Apply Perl RegExp to Remove Parenthesis and Text at End of String

查看:41
本文介绍了应用 Perl RegExp 删除字符串末尾的括号和文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,其中包含括号内的文本.如何删除字符串末尾带有文本的括号,同时将其他单词保留在字符串中?

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?

输入:

   Potatoes Rice (Meat)

输出:

   Potatoes Rice

我的代码:

#! /usr/bin/perl
use v5.10.0;
use warnings;

my $noparenthesis = "Potatoes Rice (Meat)";
$noparenthesis =~ s/^/$1/gi;
say $noparenthesis;

推荐答案

#! /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.

这篇关于应用 Perl RegExp 删除字符串末尾的括号和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆