Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

perl - How can I replace a particular character with its upper-case counterpart?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you could use a regular expression try this:

my $s = "...";
$s =~ s/([.?!]s*[a-z])/uc($1)/ge; # of course $1 , thanks to plusplus

the g-flag searches for all matches and the e-flag executes uc to convert the letter to uppercase

Explanation:

  • with [.?!] you search for your punctuation marks
  • s* is for whitespaces between the marks and the first letter of your next word and
  • [a-z] matches on a single letter (in this case the first one of the next word

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:

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;

will find ". i", "! P", ". c" and "? i" and replaces then, so the printed result is:

this is for test. I'm new to perl! Please help. Can u help? I hope so.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...