I have a problem replacing a backslash in the string K90wuRcDX43cqDB7xkjReuzb\/nDaC0xc7Bqxi4Ft0T6EscKzEBXBJ6k8fFLl6j0S.
If I manually escape the backslash in the string I have no problem
NSString *mytoken = #"K90wuRcDX43cqDB7xkjReuzb\\/nDaC0xc7Bqxi4Ft0T6EscKzEBXBJ6k8fFLl6j0S";
NSLog(#"mytoken %#",mytoken);
mytoken K90wuRcDX43cqDB7xkjReuzb\/nDaC0xc7Bqxi4Ft0T6EscKzEBXBJ6k8fFLl6j0S
But if I try to do it programmatically then I can't escape the backslash (I tried with everything: CFString, stringByReplacingOccurrencesOfString, replaceOccurrencesOfString)
NSMutableString *mytokenOrig = [NSMutableString stringWithFormat:#"K90wuRcDX43cqDB7xkjReuzb\/nDaC0xc7Bqxi4Ft0T6EscKzEBXBJ6k8fFLl6j0S"];
[mytokenOrig replaceOccurrencesOfString:#"\\" withString:#"\\\\" options:NSCaseInsensitiveSearch range:(NSRange){0,[mytokenOrig length]}];
NSLog(#"mytokenOrig %#",mytokenOrig);
mytokenOrig K90wuRcDX43cqDB7xkjReuzb/
nDaC0xc7Bqxi4Ft0T6EscKzEBXBJ6k8fFLl6j0S
Note: I have to append this token to a string and calculate a hash, so it's so important to make it work.
That is because mytokenOrig doesn't contain a backslash, it already contains the escaped new-line.
[mytokenOrig replaceOccurrencesOfString:#"\n" withString:#"\\n" options:NSCaseInsensitiveSearch range:(NSRange){0,[mytokenOrig length]}];
However, you don't need to (re)escape a string. Escape characters are for you to be able to write special characters in code.
Related
String: abc2_2fkf-lo
Now I want to use regex to delete the special characters as _ and -
The expect string as I want: abc22fkflo
Use stringByReplacingOccurrencesOfString.
NSString *string = #"abc2_2fkf-lo";
NSString *updated = [string stringByReplacingOccurrencesOfString:#"[-_]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
This replaces any occurrence of a - or _ character with the empty string.
Note that if you want to match a - character using [ ] in a regular expression, the - needs to be the first character to avoid its normal special use as a character range operator.
I am running the following code, but my regex object is always nil and the error is telling me the regex is invalid (works fine in my regex tester!)
NSError *err = nil;
NSString *pattern = #"({{[^}]*}})";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern
options: NSRegularExpressionCaseInsensitive
error: &err];
Do I need to escape anything in there? I tried adding \ before each curly brace, but that did not work either...
You need two backslashes as it is both the escape character for strings and for regular expressions, so \\ enters a single backslash into the string, and then the regular expression parser sees the backslash and escapes the brace: #"(\\{\\{[^}]*\\}\\})"
Why doesn't the comma get encoded? I was expecting it to be %2C.
(lldb) po [#"," stringByAddingPercentEscapesUsingEncoding:4]
(id) $24 = 0x0a8fbfd0 ,
As noted by #DayS, because comma is a legal URL character. However, if you would like to have control over which characters are escaped, look at CFURLCreateStringByAddingPercentEscapes().
NSString *toencode = #",";
NSString *result =
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFTypeRef)toencode,
NULL,
CFSTR(","),
kCFStringEncodingUTF8));
NSLog(#"%#", result);
This method will only replace special characters which aren't valid in a URL. As the comma is a valid one, he'll stay like this.
Try with this string to check :
[#",éà /" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
To replace other characters like comma, you have to do it yourself...
How can I replace newline (\n) sequences with one space.
I.e the user has entered a double newline ("\n\n") I want that replaced with one space (" "). Or the user has entered triple newlines ("\n\n\n") I want that replaced with also one space (" ").
Try this:
NSArray *split = [orig componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
split = [split filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"length > 0"]];
NSString *res = [split componentsJoinedByString:#" "];
This is how it works:
First line splits by newline characters
Second line removes empty items inserted for multiple separators in a row
Third line joins the strings back using a single space as the new separator
3 times more performant than using componentsSeparatedByCharactersInSet
NSString *fixed = [original stringByReplacingOccurrencesOfString:#"\\n+"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, original.length)];
Possible alternative regex patterns:
Replace only space: [ ]+
Replace space and tabs: [ \\t]+
Replace space, tabs and newlines: \\s+
Replace newlines: \\n+
As wattson says you can do this with NSRegularExpression but the code is quite verbose so if you want to do this at several places I suggestion you to do a helper method or even a NSString category with method like -[NSString stringByReplacingMatchingPattern:withString:] or something similar.
NSString *string = #"a\n\na";
NSLog(#"%#", [[NSRegularExpression regularExpressionWithPattern:#"\\n+"
options:0
error:NULL]
stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#" "]);
Use a regular expression, something like "s/\n+/\w/" (a replace which will match 1 or more newline character and replace with a single white space)
this question has a link to a regex library, but there is NSRegularExpression available too
/images/content/booking_thumbs_uk/s_kl/50000/THB_999_H54007.jpg
changes to:
/images/content/booking_thumbs_uk/s_kl/00000/THB_999_H2470.jpg
NSString* original=#"\\/images\\/content\\/booking_thumbs_uk\\/s_kl\\/50000\\/THB_999_H54007.jpg";
NSString* removed=[original stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSLog(#"%#",removed); // shows /images/content/booking_thumbs_uk/s_kl/00000/THB_999_H2470.jpg
Be very careful, because inside the source code between "..." the backslash has a special meaning. In order to represent an honest backslash, you need to double it, like "\\".
You can use newString = [oldString stringByReplacingOccurrencesOfString:#"\\" withString:#""];