I have a huge amount of NSStrings in a database that get passed to a view controller in an iOS app. They are formatted as “This is a message with $specially formatted$ content”.
However, I need to change the ‘$’ at the start of the special formatting with a ‘[‘ and the ‘$’ at the end with ‘]’. I have a feeling I can use an NSScanner but so far all of my attempts have produced wackily concatenated strings!
Is there a simple way to recognise a substring encapsulated by ‘$’ and swap them out with start/end characters? Please note that a lot of the NSStrings have multiple ‘$’ substrings.
Thanks!
You can use regular expressions:
The pattern
@"\\$([^$]*)\\$"searches forand all occurrences are then replaced by
[...]. The pattern contains so many backslashes because the$must be escaped in the regular expression pattern.There is also
stringByReplacingMatchesInStringif you want to create a new string instead of modifying the original string.