I would like the first letter after : to be uppercase using regex.
My String:
order:user:name
Expected:
Order:User:Name
CodePudding user response:
Regular expressions are very powerful and useful in many languages, but also complicated and hard to maintain if you don't fully grasp them. This is a sample without Regex. It produces the expected result, so the first word is capitalized, although it is not preceded by a ":".
my_str = "order:user:name"
new_str = my_str.split(":").map(&:capitalize).join(":")
CodePudding user response:
Use a look-back for either the start of the string or a ":"
like so (in IRB):
> my_str="order:user:name"
=> "order:user:name"
> my_str.gsub(/(?<=^|:)([a-z])/){|c| c.upcase}
=> "Order:User:Name"
CodePudding user response:
You can use this simple regex:
:[a-z]
This means, the character :
followed by any lowercase letter from a
to z
. Then you can use the gsub
method, such as in the following example:
"aa:gfdhdf:bbb".capitalize.gsub(/:[a-z]/) {|s| s[0] s[1].upcase}