I'm getting a unknown text with with 2 asterisks in it, when i need to extract the text between them
I've already tried messing with indexes, without success..
lets say I got the text
today is a *good day*
I need a string that says "good day"
I'm getting a unknown text with with 2 asterisks in it, when i need to extract the text between them
I've already tried messing with indexes, without success..
lets say I got the text
today is a *good day*
I need a string that says "good day"
You can use this regex as well :
\*(.*?)\*
You can use this function to call for regex (thanks to Swift extract regex matches):
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map { text[$0] }
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
And call:
let matched = matches(for: "\\*(.*?)\\*", in: "*good day*")
To remove asterixes you can use :
let matched = matches(for: regex, in: "*good day*").map({$0.dropFirst().dropLast()})
Note that will take all the string that start and ends with asterix, you can use firstMatch
if you need only first one.
You could get the substring between the first and last asterisks in a String, this way :
func substring(in str: String, between char: Character) -> String? {
guard var i = str.firstIndex(of: char),
let j = str.lastIndex(of: char),
i != j
else { return nil }
i = str.index(after: i)
return String(str[i..<j])
}
substring(in: "Today is a *good day*", between: "*")
If you know you have two * in the string you can do
let middle = str.components(separatedBy: "*")[1]
but there is no error handling at all here so an IndexOutOfRange might easily happen if the string content wasn't what you expected.