如何用大写字母替换特定字符?
考虑下面的字符串
String = "this is for test. i'm new to perl! Please help. can u help? I 希望如此。"
在上面 之后的字符串中。
或 ?
或 !
下一个字符应为大写。我怎样才能做到这一点?
我正在逐行读取文本文件,并且需要将修改后的数据写入另一个文件。
我们将非常感谢您的帮助。
Consider the following string
String = "this is for test. i'm new to perl! Please help. can u help? i hope so."
In the above string after .
or ?
or !
the next character should be in upper case. how can I do that?
I'm reading from text file line by line and I need to write modified data to another file.
your help will be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以使用正则表达式
试试这个:
g-flag 搜索所有匹配项,e-flag 执行 uc 将字母转换为大写
说明:
上面提到的正则表达式使用这些模式搜索下一个单词的第一个字母,以查找标点符号后跟(可选)空格和并将其替换为 uc 的结果(将匹配结果转换为大写)
例如:
将查找“.i”、“!P”、“.c”和“?i”并替换 then,因此打印结果是:
you could use a regular expression
try this:
the g-flag searches for all matches and the e-flag executes uc to convert the letter to uppercase
Explanation:
the regular expression mentioned above searches with these patterns for every appearance of a punctuation mark followed by (optional) whitespaces and a letter and replaces it with the result of uc (which converts the match to uppercase).
For example:
will find ". i", "! P", ". c" and "? i" and replaces then, so the printed result is:
您可以使用替换运算符
s///
:You can use the substitution operator
s///
:这是一个
split
解决方案:如果您所做的只是打印到一个新文件,则不需要将字符串连接起来。例如
Here's a
split
solution:If all you are doing is printing to a new file, you don't need to join the string back up. E.g.
编辑 - 完全误读了这个问题,以为您只是出于某种原因要求将
i
大写,对于任何混淆表示歉意!正如到目前为止的答案所述,您可以查看正则表达式和替换运算符
(s///)
。不过,没有人提到\b
(单词边界)字符,这对于查找单个i
可能很有用 - 否则您将不得不继续添加标点符号您找到的字符类匹配的字符([ ... ]
)。例如
给出:
edit - completely misread the question, thought you were just asking to uppercase the
i
s for some reason, apologies for any confusion!as the answers so far state, you could look at regular expressions, and the substitution operator
(s///)
. No-one has mentioned the\b
(word boundary) character though, which may be useful to find the singlei
s - otherwise you are going to have to keep adding punctuation characters that you find to the character class match (the[ ... ]
).e.g.
gives: