Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift Regex: How to find all first letter capitalized words in a string? Like a name ("My Name and another His Name")?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading