Scott W
Scott W

Reputation: 53

Swift Regex: Remove numbers embedded inside words in a String

Goal: Remove numbers embedded inside a string.

Example: let testString = "5What's9 wi3th this pro9ject I'm try905ing to build."

Desired Output: testString = "5What's9 with this project I'm trying to build"

What I've Tried:

let resultString = testString
.replacingOccurrences(of: "\\b[:digit:]\\b", with: "", options: .regularExpression)
// fails, returns string as is

let resultString = testString
    .replacingOccurrences(of: "(\\d+)", with: "", options: .regularExpression)
// fails, returns all numbers removed from string.. close

let resultString = testString
    .replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
// removes all numbers from string.. close

How can we remove numbers that are inside of words only?

Upvotes: 0

Views: 232

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

We can try doing a regex replacement on the following pattern:

(?<=\S)\d+(?=\S)

This matches only numbers surrounded on both sides by non whitespace characters. Updated code:

let resultString = testString
    .replacingOccurrences(of: "(?<=\\S)\\d+(?=\\S)", with: "", options: .regularExpression)

Upvotes: 2

Related Questions