0

Suppose I have a string "10.9.1.1", I want to get substring "10.9". How can I achieve this? So far I have the following:

var str = "10.9.1.1" let range = str.rangeOfString(".",options: .RegularExpressionSearch)! let rangeOfDecimal = Range(start:str.startIndex,end:range.endIndex) var subStr = str.subStringWithRange(rangeOfDecimal) 

But this will only return 10.

1 Answer 1

1

Actually your code returns "1" only, because "." in a regular expression pattern matches any character.

The correct pattern would be

\d+ one ore more digits \. a literal dot \d+ one or more digits 

In a Swift string, you have to escape the backslashes as "\\":

let str = "10.9.1.1" if let range = str.rangeOfString("\\d+\\.\\d+",options: .RegularExpressionSearch) { let subStr = str.substringWithRange(range) println(subStr) // "10.9" } 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, it was the regular expressions part that was bugging me!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.