GOAL: I want to have a regex that searches a string for all capitalized first letters of words/names in a string. Then replace those capitalized words with "Whatever", if the word is 4 or more characters long.
String Input:
let myString = "This is a regular string. How does this Work? Does any Name know How?"
Desired String Output:
let myString = "Whatever is a regular string. How does this Whatever? Whatever any Whatever know How?"
What I’ve tried:
if myString.contains(".*[A-Z]+.*") {
return myString.replacingOccurrences(of: "[A-Z]{4,}",
with: "Whatever",
options: .regularExpression)
}
Problems: I think the problem lies in the regex [A-Z] in the replacingOccurrences method as that searches for all caps right? But that contains(RegexComponent) fails also?
Would anyone know how to go about this with what I have? Thanks!
>Solution :
The regular expression you likely want is the following:
\b[A-Z][a-z]{3,}\b
That will only work with the basic letters A-Z and a-z. If you want to fully support any alphabet then you would need something like this:
\b\p{Lu}\p{L}{3,}\b
The \b means "word boundary". The \p{Lu} means "uppercase letters". The \p{L} means "lowercase letters".
You only want to use this in the call to replacingOccurrences. There’s little reason to do the initial check using contains. That will be looking for the literal text you pass in and of course the regular expression you are using won’t be found as literal text in the string.
let myString = "This is a regular string. How does this Work? Does any Name know How?"
let x = myString.replacingOccurrences(of: "\\b\\p{Lu}\\p{L}{3,}\\b",
with: "Whatever",
options: .regularExpression)
print(x)
Output:
Whatever is a regular string. How does this Whatever? Whatever any Whatever know How?