Use regex replacement strings

I want to transform a string containing a + with different variants. One of them is removing the + and transforming the following letter to lowercase. Currently I do this in two steps.

str = "Abdul+Hakim";
str2 = replace(str, r"\+(\p{Lu})" => lowercase);
replace(str2, "+" => "")

which results in

"Abdulhakim"

Is there a way to do this in one go? With only knowing basics of regular expressions I thought that this in principle should be possible when I have a look at

https://www.regular-expressions.info/replacecase.html

It seems like pcre2 has no case switching, so your best option is

lowercase(replace(str, '+' => ""))

If there was, it would have been

/(.+)\+(.+)/\L\1\2\E/

or

/(.+)\+(.+)/\L1\L2/

Unfortunately, that doesn’t work because then you get

"abdulhakim"

My bad, I misread the specification.

Yes, I do think the two step process is the best you can do then.

Thank’s. I thought so, but maybe I missed something or there is a package that has this functionality …

You could use the titlecase() function:

titlecase(replace(str, '+' => ""))
2 Likes
julia> replace(str, r"\+\p{Lu}" => x -> lowercase(x[2]))
"Abdulhakim"
5 Likes

Many thanks for the answers. While @rafael.guerra’s answer works in this case, because the initial letter is also uppercase, the more general solution is the one of @aplavin which really only changes the matched part. Using an anonymous function … I would have never come up with that solution :slight_smile:

You and Julia are awesome.

1 Like