0

I'm looking to split this string in 4 parts. So far i'm only able to split it using components(separatedBy:) method. However i want i also to last word teamId4 into 2 parts where i can get teamId and 4 the number. All the solutions i have looked at always have separators in them like string having either spaces, lines, full stops etc which makes it quite easy. How can i achieve this output player23, 8, teamId, 4

var player = "player23_8_chelseaId4" var splittedString: [String] { let stringArray = player.components(separatedBy: "_") let playerID = stringArray[0] let playerIndex = stringArray[1] let team = stringArray[2] // Would like "4" as the last string in the array let array = [playerID, playerIndex, team] return array } 

This is the output so far

["player23", "8", "chelseaId4"] 

Desired output would be

["player23", "8", "chelseaId", "4"] 
3
  • Is it always "Id" before the number? What if the last part is "A123B456"? Commented Jul 4, 2019 at 11:05
  • The format is static. I'm always going to receive the data in that format Commented Jul 4, 2019 at 11:08
  • Nah, 23 is always included along with the players name Commented Jul 4, 2019 at 11:11

3 Answers 3

2

This is the Regular Expression solution.

In the pattern the 4 pairs of parentheses represent the 4 captured strings, \\w+ means one or more word characters. The separators are the two underscore characters and the Id string in which the latter is captured, too.

func splittedString(from player : String) throws -> [String] { var result = [String]() let pattern = "^(\\w+)_(\\w+)_(\\w+Id)(\\w+)$" let regex = try NSRegularExpression(pattern: pattern) if let match = regex.firstMatch(in: player, range: NSRange(player.startIndex..., in: player)) { for i in 1..<match.numberOfRanges { result.append(String(player[Range(match.range(at: i), in: player)!])) } } return result } let player = "player23_8_chelseaId4" let splitted = try splittedString(from: player) // ["player23", "8", "chelseaId", "4"] 

If you want only chelsea without Id change the pattern to "^(\\w+)_(\\w+)_(\\w+)Id(\\w+)$"

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

Comments

1
var player = "player23_8_chelseaId4" var splittedString: [String] { let stringArray = player.components(separatedBy: "_") let playerID = stringArray[0] let playerIndex = stringArray[1] let team = stringArray[2] let temp = team.components(separatedBy: "Id") // Would like "4" as the last string in the array let array = [playerID, playerIndex,"\(temp[0])Id" , temp[1]] return array } print(splittedString) // ["player23", "8", "chelseaId", "4"] 

Comments

0

Is the "Id" string after every team name? So you could search for the substring Id and cut the string after it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.