1

i would like to get specific characters from my string, like this for example

var str = "hey steve @steve123, you would love this!"

// Without doing this
var theCharactersIWantFromTheString = "@steve123"

How would i just retrieve the @steve123 from str

Jaydeep Vora
  • 6,085
  • 1
  • 22
  • 40
user8426652
  • 115
  • 1
  • 8
  • You'd better clarify your requirement. The range alway starts with `@`? Or some characters can proceed `@`? Then letters (1+ or 0+?) follow and then digits? Or letters and digits can appear in arbitrary order? Or some limited symbols can be mixed? – OOPer Aug 11 '17 at 05:17
  • I only want the @symbol and albetical characters – user8426652 Aug 11 '17 at 05:21
  • You usually do not include digits in _alphabetical characters_. But your example has digits `123`. Please clarify. – OOPer Aug 11 '17 at 05:23

1 Answers1

9

You can use regular expression "\\B\\@\\w+".

let pattern = "\\B\\@\\w+"
let sentence = "hey steve @steve123, you would love this!"

if let range = sentence.range(of: pattern, options: .regularExpression) {
    print(sentence.substring(with: range))  // "@steve123\n"
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571