Objective-C: Regular expression beyond a pattern of hex value - objective-c

I'm trying to detect the text in a text view whether it contains anything beyond a pattern of hex value \u00 - \u7f or not and then do something. Please take a look at this code:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[\x00-\x7f]"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:textView.text
options:0
range:NSMakeRange(0, [textView.text length])];
if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0)))
{
// do statement 1
}
else
{
// do statement 2
}
From above, if the text view contains both text inside and outside [\u00 - \u7f] this will do statement 1 but what I want is do statement 2.
In my opinion, it should have the regular expression opposite to this pattern but I don't know what it is. Any suggestions are welcome, thank you.

A carat ('^') negates a character class, so [^\u00-\u7f] will match any character except those in the range '\u00' through '\u7f'.
You could also use rangeOfCharacterFromSet: or canBeConvertedToEncoding: to check whether a string has any non-ASCII characters.
rangeOfCharacterFromSet:
NSRange ASCIIRange = NSMakeRange(0, 0x80);
NSCharacterSet *nonASCIICharSet = [[NSCharacterSet characterSetWithRange:ASCIIRange] invertedSet];
NSRange nonASCIIChars = [textView.text rangeOfCharacterFromSet:nonASCIICharSet];
if (nonASCIIChars.location == NSNotFound) {
...
} else {
// textView.text contains non-ASCII characters
...
}
canBeConvertedToEncoding:
if ([textView.text canBeConvertedToEncoding:NSASCIIStringEncoding]) {
...
} else {
// textView.text contains non-ASCII characters
...
}

Related

Objective-C regex to remove part of string

Hi im trying to remove som HTML string from a web response. I want to remove <pre><a style="" name="output-line-1">1</a>, were the who instances of number "1"varies, but is always a digit. but how do i write the regex method for removing this? Below is what i have got so far:
-(NSString *)stringByStrippingHTML:(NSString*)str
{
NSRange r;
while ((r = [str rangeOfString:#"/^<pre><a style=\"\"name=\"output-line-([0-9])\">([0-9])</a>" options:NSRegularExpressionSearch]).location != NSNotFound){
str = [str stringByReplacingCharactersInRange:r withString:#""];
}
}
Basically I want to remove a substring with random number in it... In some instances of the substring the 1 is replaced, so that any similar string gets acknowledged, for example it could be output-line-999. How do i combine the range of string so i can both describe the string and specify to find any similar string with any number?
I want to remove both the HTML and the numbers.
This regular expression should work:
[str rangeOfString:#"<pre><a style=\"\" name=\"output-line-[0-9]+\">[0-9]+</a>" options:NSRegularExpressionSearch];
I thnk the problem is that there ins't a space before name in your reg expression
Using your original while loop, you can:
-(NSString *)stringByStrippingHTML:(NSString*)str
{
NSRange r;
while ((r = [str rangeOfString:#"<pre><a style=\"\" name=\"output-line-[0-9]+\">[0-9]+</a>" options:NSRegularExpressionSearch]).location != NSNotFound)
{
str = [str stringByReplacingCharactersInRange:r withString:#""];
}
}
Or you can use NSRegularExpression:
NSMutableString *input = ...
NSError *error;
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:#"<pre><a style=\"\" name=\"output-line-[0-9]+\">[0-9]+</a>"
options:0
error:&error];
if (error)
{
NSLog(#"error=%#",error);
return;
}
[regex replaceMatchesInString:input
options:0
range:NSMakeRange(0, [input length])
withTemplate:#""];

Objective-C Case-Insensitivity and Turkish Characters

I have a regular expression that searches strings and then wraps them within certain html tags. The problem is that two Turkish characters (İ and ı) do not get matched against their lower or upper cases. So they cannot be wrapped properly.
To be more precise:
i and even İ is not matched against İ (it probably becomes "I")
I is not matched against ı (it probably becomes "i")
Example:
Search term is İskendername.
The string contains it exactly as it is (İskendername) but there are no matches at all.
Here is my code:
NSString *regex_pattern = [[NSArray arrayWithObjects:#"(", search_term, #")(?![^<>]*>)",nil] componentsJoinedByString:#""];
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:regex_pattern options:NSRegularExpressionCaseInsensitive error:&error];
string_to_be_searched = [regex stringByReplacingMatchesInString:string_to_be_searched options:0 range:NSMakeRange(0, [stringByReplacingMatchesInString:string_to_be_searched length]) withTemplate:#"<div class=""highlight"">$1</div>"];
Solved it myself. Here is how:
There was no way I could get any kind of NS.. options to support Turkish characters. A lossy conversion causes defect in my rendered content. So here is how I sorted it out:
As I have stated, there is this problem that -I- is understood as -i- and -i- is treated as I but that is not the case with Turkish alphabet. We have a lowercase -ı- and an uppercase -İ-.
What I have done was changing my regular expression. So basically I went through all the letters in the NSString and replaced problematic ones (I and i) with [iİıI] so my regular expression would accept them regardless of their having a dot on top or not !
Here is the code in case someone needs it..
- (NSString*)returnRegexPatternForSearchString:(NSString *)search_string
{
NSString *regex_pattern = [[NSString alloc] init];
for(int i =0 ;i<[search_string length]; i++)
{
if([[search_string substringWithRange:NSMakeRange(i, 1)] isEqualToString:#"ı"] || [[search_string substringWithRange:NSMakeRange(i, 1)] isEqualToString:#"I"])
{
regex_pattern = [regex_pattern stringByAppendingString:#"[ıI]"];
}
else if([[search_string substringWithRange:NSMakeRange(i, 1)] isEqualToString:#"i"] || [[search_string substringWithRange:NSMakeRange(i, 1)] isEqualToString:#"İ"])
{
regex_pattern = [regex_pattern stringByAppendingString:#"[iİıI]"];
}
else
{
regex_pattern = [regex_pattern stringByAppendingString:[search_string substringWithRange:NSMakeRange(i, 1)]];
}
}
return regex_pattern;
}

Objective-C NSString character substitution

I have a NSString category I am working on to perform character substitution similar to PHP's strtr. This method takes a string and replaces every occurrence of each character in fromString and replaces it with the character in toString with the same index. I have a working method but it is not very performant and would like to make it quicker and able to handle megabytes of data.
Edit (for clarity):
stringByReplacingOccurrencesOfString:withString:options:range: will not work. I have to take a string like "ABC" and after replacing "A" with "B" and "B" with "A" end up with "BAC". Successive invocations of stringByReplacingOccurrencesOfString:withString:options:range: would make a string like "AAC" which would be incorrect.
Suggestions would be great, sample code would be even better!
Code:
- (NSString *)stringBySubstitutingCharactersFromString:(NSString *)fromString
toString:(NSString *)toString;
{
NSMutableString *substitutedString = [self mutableCopy];
NSString *aCharacterString;
NSUInteger characterIndex
, stringLength = substitutedString.length;
for (NSUInteger i = 0; i < stringLength; ++i) {
aCharacterString = [NSString stringWithFormat: #"%C", [substitutedString characterAtIndex:i]];
characterIndex = [fromString rangeOfString:aCharacterString].location;
if (characterIndex == NSNotFound) continue;
[substitutedString replaceCharactersInRange:NSMakeRange(i, 1)
withString:[NSString stringWithFormat:#"%C", [toString characterAtIndex:characterIndex]]];
}
return substitutedString;
}
Also this code is executed after every change to text in a text view. It is passed the entire string every time. I know that there is a better way to do it, but I do not know how. Any suggestions for this would be most certainly appreciated!
You can make that kind of string substitution with NSRegularExpression either modifying an mutable string or creating a new immutable string. It will work with any two strings to substitute (even if they are more than one symbol) but you will need to escape any character that means something in a regular expression (like \ [ ( . * ? + etc).
The pattern finds either of the two substrings with the optional "anything" between and than replaces them with the two substrings with each other preserving the optional string between them.
// These string can be of any length
NSString *firstString = #"Axa";
NSString *secondString = #"By";
// Escaping of characters used in regular expressions has NOT been done here
NSString *pattern = [NSString stringWithFormat:#"(%#|%#)(.*?)(%#|%#)", firstString, secondString, firstString, secondString];
NSString *string = #"AxaByCAxaCBy";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:&error];
if (error) {
// Insert error handling here...
}
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"$3$2$1"];
NSLog(#"Before:\t%#", string); // AxaByCAxaCBy
NSLog(#"After: \t%#", modifiedString); // ByAxaCByCAxa

Objective c: Comparing String on basis of common pattern

I have two strings.
NSString *a=#"1_2";
NSString *b=#"1_3";
I want to compare these two string .I want that these two string should be equal. By equal I mean first two characters are the same.
Is there any method which can compare these two string?
Here's a method to compare only the first two characters:
- (NSComparisonResult)compareFirstTwoCharactersOf:(NSString *)str1 with:(NSString *)str2
{
if ([str1 length] < 2) {
// Receiver too short, fall back.
return [str1 compare:str2];
} else {
return [str1 compare:str2 options:0 range:NSMakeRange(0, 2)];
}
}
if ([a isEqualToString:b]) {
NSLog(#"equal");
}
if ([[a substringToIndex:2] isEqualToString:[b substringToIndex:2]]) {
NSLog(#"equal");
}
You should use regular expressions. You should create a regular expression that corresponds to "digit underscore digit", and then if a and b fit the expression then they both are "equal" the way you want them to be, not literally equal of course.
Check this out:
https://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html
As an example, a regular expression that matches "digit underscore digit" should be: \d_\d
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\d_\d" options:0 error:NULL];
NSString *a = #"1_2";
NSString *b = #"1_3";
NSTextCheckingResult *matchA = [regex firstMatchInString:a options:0 range:NSMakeRange(0, [a length])];
NSTextCheckingResult *matchB = [regex firstMatchInString:b options:0 range:NSMakeRange(0, [b length])];
if(matchA && matchB){
//Strings match the same pattern
}

How to capitalize the first word of the sentence in Objective-C?

I've already found how to capitalize all words of the sentence, but not the first word only.
NSString *txt =#"hi my friends!"
[txt capitalizedString];
I don't want to change to lower case and capitalize the first char. I'd like to capitalize the first word only without change the others.
Here is another go at it:
NSString *txt = #"hi my friends!";
txt = [txt stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[txt substringToIndex:1] uppercaseString]];
For Swift language:
txt.replaceRange(txt.startIndex...txt.startIndex, with: String(txt[txt.startIndex]).capitalizedString)
The accepted answer is wrong. First, it is not correct to treat the units of NSString as "characters" in the sense that a user expects. There are surrogate pairs. There are combining sequences. Splitting those will produce incorrect results. Second, it is not necessarily the case that uppercasing the first character produces the same result as capitalizing a word containing that character. Languages can be context-sensitive.
The correct way to do this is to get the frameworks to identify words (and possibly sentences) in the locale-appropriate manner. And also to capitalize in the locale-appropriate manner.
[aMutableString enumerateSubstringsInRange:NSMakeRange(0, [aMutableString length])
options:NSStringEnumerationByWords | NSStringEnumerationLocalized
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[aMutableString replaceCharactersInRange:substringRange
withString:[substring capitalizedStringWithLocale:[NSLocale currentLocale]]];
*stop = YES;
}];
It's possible that the first word of a string is not the same as the first word of the first sentence of a string. To identify the first (or each) sentence of the string and then capitalize the first word of that (or those), then surround the above in an outer invocation of -enumerateSubstringsInRange:options:usingBlock: using NSStringEnumerationBySentences | NSStringEnumerationLocalized. In the inner invocation, pass the substringRange provided by the outer invocation as the range argument.
Use
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
and capitalize the first object in the array and then use
- (NSString *)componentsJoinedByString:(NSString *)separator
to join them back
pString = [pString
stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[pString substringToIndex:1] capitalizedString]];
you can user with regular expression i have done it's works for me simple you can paste below code
+(NSString*)CaptializeFirstCharacterOfSentence:(NSString*)sentence{
NSMutableString *firstCharacter = [sentence mutableCopy];
NSString *pattern = #"(^|\\.|\\?|\\!)\\s*(\\p{Letter})";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL];
[regex enumerateMatchesInString:sentence options:0 range:NSMakeRange(0, [sentence length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
//NSLog(#"%#", result);
NSRange r = [result rangeAtIndex:2];
[firstCharacter replaceCharactersInRange:r withString:[[sentence substringWithRange:r] uppercaseString]];
}];
NSLog(#"%#", firstCharacter);
return firstCharacter;
}
//Call this method
NsString *resultSentence = [UserClass CaptializeFirstCharacterOfSentence:yourTexthere];
An alternative solution in Swift:
var str = "hello"
if count(str) > 0 {
str.splice(String(str.removeAtIndex(str.startIndex)).uppercaseString, atIndex: str.startIndex)
}
For the sake of having options, I'd suggest:
NSString *myString = [NSString stringWithFormat:#"this is a string..."];
char *tmpStr = calloc([myString length] + 1,sizeof(char));
[myString getCString:tmpStr maxLength:[myString length] + 1 encoding:NSUTF8StringEncoding];
int sIndex = 0;
/* skip non-alpha characters at beginning of string */
while (!isalpha(tmpStr[sIndex])) {
sIndex++;
}
toupper(tmpStr[sIndex]);
myString = [NSString stringWithCString:tmpStr encoding:NSUTF8StringEncoding];
I'm at work and don't have my Mac to test this on, but if I remember correctly, you couldn't use [myString cStringUsingEncoding:NSUTF8StringEncoding] because it returns a const char *.
In swift you can do it as followed by using this extension:
extension String {
func ucfirst() -> String {
return (self as NSString).stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: (self as NSString).substringToIndex(1).uppercaseString)
}
}
calling your string like this:
var ucfirstString:String = "test".ucfirst()
I know the question asks specifically for an Objective C answer, however here is a solution for Swift 2.0:
let txt = "hi my friends!"
var sentencecaseString = ""
for (index, character) in txt.characters.enumerate() {
if 0 == index {
sentencecaseString += String(character).uppercaseString
} else {
sentencecaseString.append(character)
}
}
Or as an extension:
func sentencecaseString() -> String {
var sentencecaseString = ""
for (index, character) in self.characters.enumerate() {
if 0 == index {
sentencecaseString += String(character).uppercaseString
} else {
sentencecaseString.append(character)
}
}
return sentencecaseString
}