正则表达式和字符大小写
好吧,我得到了一个相当简单的(至少看起来很简单)。我有一个多行字符串,我只是在尝试用其他东西替换不同的单词。让我告诉你...
#!/usr/bin/perl -w
use strict;
$_ = "That is my coat.\nCoats are very expensive.";
s/coat/Hat/igm;
print;
输出将是那是我的帽子
帽子非常昂贵...
第一行的“hat”不应该大写。有什么技巧可以让大小写符合英文的书写方式吗?谢谢 :)
Okay, I got a rather simple one (at least seems simple). I have a multi lined string and I am just playing around with replacing different words with something else. Let me show you...
#!/usr/bin/perl -w
use strict;
$_ = "That is my coat.\nCoats are very expensive.";
s/coat/Hat/igm;
print;
The output would beThat is my Hat
Hats are very expensive...
The "hat" on the first line shouldn't be capitalized. Are there any tricks that can make the casing compliant with how english is written? Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请参阅如何替换-string-and- keep-its-uppercase-lowercase
有关更多详细信息,请访问如何在 LHS 上不区分大小写地替换,同时在 RHS 上保留大小写?
see how-to-replace-string-and-preserve-its-uppercase-lowercase
For more detail go to How do I substitute case insensitively on the LHS while preserving case on the RHS?
您可以使用
e
修饰符到s///
来实现此目的:You can use the
e
modifier tos///
to do the trick:其一,您应该使用
\b
(单词边界)来仅匹配整个单词。例如,s/hat/coat/
会将That
更改为Tcoat
,而无需前导\b
。现在回答你的问题。使用标志/e
您可以在正则表达式的替换部分中使用 Perl 代码。因此,您可以编写一个 Perl 函数来检查匹配的大小写,然后正确设置替换的大小写:
For one, you should use
\b
(word boundary) to match only the whole word. For examples/hat/coat/
would changeThat
toTcoat
without leading\b
. Now for your question. With the flag/e
you can use Perl code in the replacement part of the regex. So you can write a Perl function that checks the case of the match and then set the case of the replacement properly:Prints:
这可能会解决您的问题:
This may solve your problem: