-2

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"

Golan Gil
  • 11
  • 1
  • 1
    What if the string is `"zero *one*two* *three* "`, `"zero *one"`, or `"zero *"`, what should be the result? – ielyamani Mar 31 '19 at 13:43

3 Answers3

0

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.

Miknash
  • 7,888
  • 3
  • 34
  • 46
0

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: "*") 
ielyamani
  • 17,807
  • 10
  • 55
  • 90
0

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.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52