Swift Get String Between 2 Strings in a String

Swift Get string between 2 strings in a string

I'd use a regular expression to extract substrings from complex input like this.

Swift 3.1:

let test = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"

if let match = test.range(of: "(?<=')[^']+", options: .regularExpression) {
print(test.substring(with: match))
}

// Prints: Info/99/something

Swift 2.0:

let test = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"

if let match = test.rangeOfString("(?<=')[^']+", options: .RegularExpressionSearch) {
print(test.substringWithRange(match))
}

// Prints: Info/99/something

Get string between two strings Swift

Use components(separatedBy:):

var str = "Notes[9219:1224244] [BoringSSL] Function boringssl_context_get_peer_sct_list: line 1757 received sct extension length is less than sct data length [[[\"encendedor\",\"lighter\",null,null,1]],null,\"en\"]"

str.components(separatedBy: "\"")[1] // "encendedor"

iOS Get String between 2 Strings

You where nearly there, but the range location is the start of the not the end. So you have to add the length of the range.

Since the you moved the start of you string, you need to short the length with the offset:

NSString *serverOutput = @"<id>100</id>";
NSRange startRange = [serverOutput rangeOfString:@"<id>"];
NSRange endRange = [serverOutput rangeOfString:@"</id>"];

NSInteger start = NSMaxRange (startRange);
NSInteger length = endRange.location - startRange.length;

NSLog(@"%@", [serverOutput substringWithRange:NSMakeRange(start, length)]);

Finding a string between two ranges of strings or end of string

You may use

(?<=start\s).*?(?=\s+(?:then|stop|other)|$)

See the regex demo. To search for whole words, add \b word boundary in proper places:

(?<=\bstart\s).*?(?=\s+(?:then|stop|other)\b|$)

See another regex demo

Details

  • (?<=start\s) - a positive lookbehind that matches a location immediately preceded with start string and a whitespace
  • .*? - any 0+ chars other than line break chars, as few as possible
  • (?=\s+(?:then|stop|other)|$) - a position in the string that is immediately followed with
    • \s+ - 1+ whitespaces
    • (?:then|stop|other) - one of the words
    • |$ - or end of string.

regex to get string between two % characters

Your pattern is fine but your code didn't compile. Try this instead:

Swift 4

let query = "Hello %test% how do you do %test1%"
let regex = try! NSRegularExpression(pattern:"%(.*?)%", options: [])
var results = [String]()

regex.enumerateMatches(in: query, options: [], range: NSMakeRange(0, query.utf16.count)) { result, flags, stop in
if let r = result?.range(at: 1), let range = Range(r, in: query) {
results.append(String(query[range]))
}
}

print(results) // ["test", "test1"]

NSString uses UTF-16 encoding so NSMakeRange is called with the number of UTF-16 code units.

Swift 2

let query = "Hello %test% how do you do %test1%"
let regex = try! NSRegularExpression(pattern:"%(.*?)%", options: [])
let tmp = query as NSString
var results = [String]()

regex.enumerateMatchesInString(query, options: [], range: NSMakeRange(0, tmp.length)) { result, flags, stop in
if let range = result?.rangeAtIndex(1) {
results.append(tmp.substringWithRange(range))
}
}

print(results) // ["test", "test1"]

Getting a substring out of Swift's native String type is somewhat of a hassle. That's why I casted query into an NSString

Replace string between characters in swift

A simple regular expression:

let sentence = "This is \"table\". There is an \"apple\" on the \"table\""

let pattern = "\"[^\"]+\"" //everything between " and "
let replacement = "____"
let newSentence = sentence.replacingOccurrences(
of: pattern,
with: replacement,
options: .regularExpression
)

print(newSentence) // This is ____. There is an ____ on the ____

If you want to keep the same number of characters, then you can iterate over the matches:

let sentence = "This is table. There is \"an\" apple on \"the\" table."    
let regularExpression = try! NSRegularExpression(pattern: "\"[^\"]+\"", options: [])

let matches = regularExpression.matches(
in: sentence,
options: [],
range: NSMakeRange(0, sentence.characters.count)
)

var newSentence = sentence

for match in matches {
let replacement = Array(repeating: "_", count: match.range.length - 2).joined()
newSentence = (newSentence as NSString).replacingCharacters(in: match.range, with: "\"" + replacement + "\"")
}

print(newSentence) // This is table. There is "__" apple on "___" table.

Swift get the different characters in two strings

UPDATE for Swift 4.0 or greater

Because of the change of String to also be a collection, this answer can be shortened to

let difference = zip(x, y).filter{ $0 != $1 }

For Swift version 3.*

let difference = zip(x.characters, y.characters).filter{$0 != $1}

Sample Image



Related Topics



Leave a reply



Submit