How can I replace special characters by regex and Objective-C? - objective-c

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.

Related

Replace special character or whitespace with -

I want to make every string look like this:
"this-is-string-one"
So main string could contain:
"This! is string, one"
So basicaly replace !?., whitespace and characters like that with "-".
Something like this is best handled by a regular expression:
NSString *someString = #"This! is string, one";
NSString *newString = [someString stringByReplacingOccurrencesOfString:#"[!?., ]+" withString:#"-" options: NSRegularExpressionSearch range:NSMakeRange(0, someString.length)];
NSLog(#"\"%#\" was converted to \"%#\"", someString, newString);
The output will be:
"This! is string, one" was converted to "This-is-string-one"
The regular expression [!?., ]+ means any sequence of one or more of the characters listed between the square brackets.
Update:
If you want to truncate any trailing hyphen then you can do this:
if ([newString hasSuffix:#"-"]) {
newString = [newString substringToIndex:newString.length - 1];
}

Objective-C – Replace newline sequences with one space

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

How to omit a certain substring out of an NSString?

I would like to know how it is possible to omit a specific substring out an NSString, assuming the NSString does contain that substring.
For example:
Original string: "This is a string but these words should be omitted."
Substring to omit: "but these words should be omitted".
Result string: "This is a string."
Thanks ahead,
iLyrical.
NSString *originalString = #"This is a string but these words should be omitted.";
NSString *substringToOmit = #" but these words should be omitted";
NSString *resultString = [originalString stringByReplacingOccurencesOfString:substringToOmit
withString:#""];
See NSString's stringByReplacingOccurrencesOfString:withString:. You may also want to trim the trailing whitespace with stringByTrimmingCharactersInSet:.

searching and replacing an extended ASCII in a string

a noob question here.
I am trying to make an automatic search and replace process for characters' ASCII values in a string.
so, I have a string constructed from a content of a UITextField
NSString *searchText;
searchText = (mmText.text);
then I do a little loop and check all entered characters for their ASCII values. if they're not in the allowed range I want to search and replace them with something else (? for now)
so let's say I am in the loop and I get to a ASCII 45 character (it's a minus sign):
int asciiCode = 45;
now I would like to find the ASCII 45 character in the string and replace it with a question mark
This is what I am doing at the moment:
NSString *ascStr = [NSString stringWithFormat:#"%c", asciiCode];
NSRange matchSpace;
matchSpace = [searchText rangeOfString: ascStr];
if (matchSpace.location == NSNotFound)
{}
else
NSMutableString *searchandReplace = [NSMutableString stringWithString: searchText];
[searchandReplace replaceCharactersInRange: [searchandReplace rangeOfString: ascStr] withString: #"?"];
mmText.text = searchandReplace;
}
This works fine for a regular ASCII value (0-255), but it doesn't seem to work for the extended ASCII values coming from foreign languages. For example when using the Korean language mode, one of the main character looks like a double crossed W, but when printed via NSLog it looks like a copyright sign. This is probably the reason the search and replace procedure doesn't work for it. It has an ASCII value of 8361.
any ideas ? thank you!
it turns out it was as simple as changing:
NSString *ascStr = [NSString stringWithFormat:#"%c", asciiCode];
to
NSString *ascStr = [NSString stringWithFormat:#"%C", asciiCode];
%c
8-bit unsigned character (unsigned char), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit
%C
16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit

Objective-C Check for Unallowed Characters in String

How would I, in objective-c, make it so only strings with a-z characters were allowed? I.E. no & characters, no - characters, etc.
Thanks!
Christian Stewart
NSCharacterSets are going to be the key here. First you'll need the character set of alphabetical characters:
NSCharacterSet* letters = [NSCharacterSet characterSetWithRange:NSMakeRange('a', 26)];
And then, if you want to check if the string contains a character that's not a letter, you can use this set's inverse:
NSCharacterSet* notLetters = [letters invertedSet];
Then use NSString's rangeOfCharacterFromSet: with notLetters, and if the range doesn't start with NSNotFound, there are forbidden characters in your string.
NSRange badCharacterRange = [myString rangeOfCharacterFromSet:notLetters];
if (badCharacterRange.location != NSNotFound) // found bad characters