考虑以下字符串
String = “这是为了测试。我是perl的新手!请帮助。你可以帮忙吗?我希望如此。”
在.
或?
或!
之后的上述字符串中,下一个字符应为大写。我怎么能这样做?
我正在逐行读取文本文件,我需要将修改后的数据写入另一个文件。
非常感谢您的帮助。
答案 0 :(得分:12)
你可以使用正则表达式 试试这个:
my $s = "...";
$s =~ s/([\.\?!]\s*[a-z])/uc($1)/ge; # of course $1 , thanks to plusplus
g-flag搜索所有匹配项,e-flag执行uc将字母转换为大写
说明:
上面提到的正则表达式使用这些模式搜索标点符号的每个外观,后跟(可选)空格和字母,并将其替换为uc的结果(将匹配转换为大写)。
例如:
my $s = "this is for test. i'm new to perl! Please help. can u help? i hope so.";
$s =~ s/([\.\?!]\s*[a-z])/uc(&1)/ge;
print $s;
会找到“.i”,“!P”,“。c”和“?i”然后替换,所以打印结果是:
this is for test. I'm new to perl! Please help. Can u help? I hope so.
答案 1 :(得分:2)
您可以使用替换运算符s///
:
$string =~ s/([.?!]\s*\S)/ uc($1) /ge;
答案 2 :(得分:1)
这是一个split
解决方案:
$str = "this is for test. im new to perl! Please help. can u help? i hope so.";
say join "", map ucfirst, split /([?!.]\s*)/, $str;
如果你要做的只是打印到一个新文件,你不需要重新加入字符串。 E.g。
while ($line = <$input>) {
print $output map ucfirst, split /([?!.]\s*)/, $line;
}
答案 3 :(得分:0)
编辑 - 完全误读了这个问题,认为你只是因为某种原因要求大写i
,对任何混淆道歉!
作为目前为止的答案,您可以查看正则表达式和替换运算符(s///)
。没有人提到\b
(单词边界)字符,这可能对查找单个i
有用 - 否则你将不得不继续添加你找到的标点符号字符类匹配([ ... ]
)。
e.g。
my $x = "this is for test. i'm new to perl! Please help. can u help? i hope so. ".
\"i want it to work!\". Dave, Bob, Henry viii and i are friends. foo i bar.";
$x =~ s/\bi\b/I/g; # or could use the capture () and uc($1) in eugene's answer
给出:
# this is for test. I'm new to perl! Please help. can u help? I hope so.
# "I want it to work!". Dave, Bob, Henry viii and I are friends. foo I bar.