1

Here is my question, I have a string array that contains a bunch of countries:

let myCountryStart = ["Africa/ABC", "America/BBC", "Asia/CBC", "Pacific/CBA", "Europe/CBB", "Indian/CAB"]

Is there have any solution to remove the specific words like 'Africa', 'America', 'Asia'...etc,. Let the output result looks like the below followings:

let myCountryEnd = ["ABC", "BBC", "CBC", "CBA", "CBB", "CAB"]

Here are my code for now...

let 1stReplace = myCountryStart.replacingOccurrences(of: "/", with: "", options: .literal)
let 2ndReplace = 1stReplace.replacingOccurrences(of: "Africa", with: "", options: .literal)
let 3rdReplace = 2ndReplace.replacingOccurrences(of: "Asia", with: "", options: .literal)

I know this is a stupid solution. Hence, I prefer to use NSRegular Expression. But I encountered a problem about String & String Array issue.

let target = myCountryStart
let regex = "/"
let RE = try? NSRegularExpression(pattern: "regex", options: .caseInsensitive)
let modified = RE?.stringByReplacingMatches(in: target, options: .reportProgress, range: nil, withTemplate: "") {
    return modified
}
let myCountryEnd = modified

Therefore, I got a warning about I cannot use this method on String array. What should I do to fix it?

Any suggestions or help will be greatly appreciated. Thanks from a Swift rookie.

6
  • myCountryStart seems to only have one element. Is that true? Commented May 25, 2020 at 7:59
  • What is outputStrin your old code? Why don't you use that, instead of myCountryStart in your new code? Commented May 25, 2020 at 8:01
  • It should be six elements of a string array. I forgot to revise it. Commented May 25, 2020 at 8:06
  • @Sweeper Thanks for notice me about that old code error. Commented May 25, 2020 at 8:09
  • 2
    You didn't change it to 6 elements in your edit though... Commented May 25, 2020 at 8:10

1 Answer 1

2

You may use .map and .replacingOccurrences using a regex like .*/ or ^[^/]*/:

let myCountryStart = ["Africa/ABC", "America/BBC", "Asia/CBC", "Pacific/CBA", "Europe/CBB", "Indian/CAB"]
let myCountryEnd = myCountryStart.map{ $0.replacingOccurrences(of: ".*/", with: "", options: [.caseInsensitive,.regularExpression]) }
print(myCountryEnd)
// => ["ABC", "BBC", "CBC", "CBA", "CBB", "CAB"]

The .*/ pattern will match any 0 or more characters other than line break chars, as many as possible, up to the last /.

The ^[^/]*/ pattern will match any chars other than / from the start of the string till the first /.

Note you do not need the .caseInsensitive option, I kept it to show how you may combine several options in the options argument.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.