Home > Enterprise >  Swift Regex: Remove numbers embedded inside words in a String
Swift Regex: Remove numbers embedded inside words in a String

Time:11-09

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?

CodePudding user response:

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)
  • Related