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
  • 5,615
  • 1
  • 20
  • 38
user8426652
  • 105
  • 1
  • 6
  • 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

8

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
  • 198,248
  • 51
  • 423
  • 494