Regex for a string combination - ios

NSString *fmtpAudio = #"a=fmtp:111 ";
NSString *stereoString = #";stereo=1;sprop-stereo=1";
NSArray *componentArray = [localSdpMutableStr componentsSeparatedByString:fmtpAudio];
if (componentArray.count >= 2) {
NSString *component = [componentArray objectAtIndex: 1];
NSArray *fmtpArray = [component componentsSeparatedByString:#"\r\n"];
if (fmtpArray.count > 1) {
NSString *fmtp = [fmtpArray firstObject];
NSString *fmtpAudioOld = [NSString stringWithFormat:#"%#%#", fmtpAudio, fmtp];
fmtpAudio = [NSString stringWithFormat:#"%#%#%#", fmtpAudio, fmtp, stereoString];
NSString *stereoEnabledSDP = [NSString stringWithString: localSdpMutableStr];
stereoEnabledSDP = [stereoEnabledSDP stringByReplacingOccurrencesOfString: fmtpAudioOld withString: fmtpAudio];
localSdpMutableStr.string = stereoEnabledSDP;
}
}
Consider below example String:
a=fmtp:93 av=2\r\n
a=fmtp:111 av=1\r\n
a=fmtp:92 av=2\r\n
In the above example string, a=fmtp:111 can appear anywhere in the string.
We have to get the string between a=fmtp:111 and the next first appearance of \r\n which is av=1 in our case
Now we have to append ;stereo=1;sprop-stereo=1 to av=1 and append back to the original string.
The final output should be
a=fmtp:93 av=2\r\n
a=fmtp:111 av=1;stereo=1;sprop-stereo=1\r\n
a=fmtp:92 av=2\r\n
Is it possible to achieve the above chunk of logic with Replace with Regex pattern?

You can use
NSError *error = nil;
NSString *fmtpAudio = #"^a=fmtp:111 .*";
NSString *stereoString = #"$0;stereo=1;sprop-stereo=1";
NSString *myText = #"a=fmtp:93 av=2\r\na=fmtp:111 av=1\r\na=fmtp:92 av=2";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:fmtpAudio options:NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate: stereoString];
NSLog(#"%#", modifiedString);
Output:
a=fmtp:93 av=2
a=fmtp:111 av=1;stereo=1;sprop-stereo=1
a=fmtp:92 av=2
See the regex demo.
Details
^ - start of a line (^ starts matching line start positions due to the options:NSRegularExpressionAnchorsMatchLines option)
a=fmtp:111 - a literal string
.* - any zero or more chars other than line break chars as many as possible.
The $0 in the replacement pattern is the backreference to the whole match value.

Related

Use regular expression to find and replace the string from Textfield in NSString

I would like to use regular expression to find and replace the string. In my scenario {3} and {2} are UITextField tag values. Based on the tag value, I would like to replace the respective textfield values and calculate the string value using NSExpression.
Sample Input String :
NSString *cumputedValue = #"{3}*0.42/({2}/100)^2";
Note: The textFields are created dynamically based on JSON response.
I got the answer for this question. Here the computedString contains the value as "{3}*0.42/({2}/100)^2".
- (NSString *)autoCalculationField: (NSString *)computedString {
NSString *computedStringFormula = [NSString stringWithFormat:#"%#",computedString];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\{(\\d+)\\}"
options:0
error:nil];
NSArray *matches = [regex matchesInString:computedStringFormula
options:0
range:NSMakeRange(0, computedStringFormula.length)];
NSString *expressionStr = computedStringFormula;
for (NSTextCheckingResult *r in matches)
{
NSRange numberRange = [r rangeAtIndex:1];
NSString *newString = [NSString stringWithFormat:#"%.2f",[self getInputFieldValue:[computedStringFormula substringWithRange:numberRange]]];
expressionStr = [expressionStr stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"{%#}",[computedStringFormula substringWithRange:numberRange]] withString:newString];
}
NSExpression *expression = [NSExpression expressionWithFormat:expressionStr];
return [expression expressionValueWithObject:nil context:nil];
}
- (float)getInputFieldValue: (NSString *)tagValue {
UITextField *tempTextFd = (UITextField *)[self.view viewWithTag:[tagValue intValue]];
return [tempTextFd.text floatValue];
}
You could save the textField tags in a NSDictionary with the value that they represent.
After that use stringByReplacingOccurrencesOfString to replace the values that you wish to.
Something like this:
for (NSString *key in dict) {
cumputedValue = [cumputedValue stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"{#%}", key] withString:[NSString stringWithFormat:#"%#", dict objectForKey:#key]];
}
This way you can have the values replaced

How to add a character at start and end of every word in NSString

Suppose i have this:
NSString *temp=#"its me";
Now suppose i want ' " ' in start and end of every word, how can i achieve it to get the result like this:
"its" "me"
Do i have to use regular expressions?
If you have punctuation inside the string, splitting with a space might not be enough.
Use the word boundary \b: it matches both the leading and trailing word boundaries (that is, it will match an empty space right between word and non-word characters and also at the start/end of the string if followed/preceded with a word character.
NSError *error = nil;
NSString *myText = #"its me";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\b" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:#"\""];
NSLog(#"%#", modifiedString); // => "its" "me"
See the IDEONE demo
See more details on the regex syntax in Objective C here.
You can do something like,
NSString *str = #"its me";
NSMutableString *resultStr = [[NSMutableString alloc]init];
NSArray *arr = [str componentsSeparatedByString:#" "];
for (int i = 0; i < arr.count; i++) {
NSString *tempStr = [NSString stringWithFormat:#"\"%#\"",arr[i]];
resultStr = [resultStr stringByAppendingString:[NSString stringWithFormat:#"%# ",tempStr]];
}
NSLog(#"result string is : %#",resultStr);
Hope this will help :)

Extract a String out of a specific set of strings

I have a text as:
sometext[string1 string2]someText
I want to retrieve string1 and string2 as separate strings from this text
How can i parse it in objective - c?
i have found the solution
NSArray *arrayOne = [prettyFunctionString componentsSeparatedByString:#"["];
NSString *parsedOne = [arrayOne objectAtIndex:1];
NSArray *arrayTwo = [parsedOne componentsSeparatedByString:#"]"];
NSString *parsedTwo = [arrayTwo objectAtIndex:0];
NSArray *arrayThree = [parsedTwo componentsSeparatedByString:#" "];
NSString *className = [arrayThree objectAtIndex:0];
NSString *functionName = [arrayThree objectAtIndex:1];
thanks anyways
Maybe something like this could work for you
NSString * string = #"sometext[string1 string2]sometext";
NSString * pattern = #"(.*)\[(.+) (.+)\](.*)"
NSRegularExpression * expression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:NULL];
NSTextCheckingResult * match = [expression firstMatchInString:string options:NSMatchingReportCompletion range:NSMakeRange(0, string.length)];
if (match) {
NSString * substring1 = [string substringWithRange:[match rangeAtIndex:2]];
NSString * substring2 = [string substringWithRange:[match rangeAtIndex:3]];
// do something with substring1 and substring2
}
You can Use this Simple Approach approach
NSString *str = #"sometext[string1 string2]someText";
NSInteger loc1 = [str localizedStandardRangeOfString:#"["].location;
NSInteger loc2 = [str localizedStandardRangeOfString:#"]"].location;
NSString *resultString = [str substringWithRange:(NSRange){loc1+1,loc2-loc1}];
NSArray *resultArry = [resultString componentsSeparatedByString:#" "];
result array will contain your required Reuslt
For completeness - if you are trying to extract strings out of a string with a known pattern, then an NSScanner is the way to go.
This goes through the string in one pass.
NSString *string = #"sometext[string1 string2]someText";
NSScanner *scanner = [NSScanner scannerWithString:string];
NSString *str1;
NSString *str2;
[scanner scanUpToString:#"[" intoString:nil]; // Scan up to the '[' character.
[scanner scanString:#"[" intoString:nil]; // Scan the '[' character and discard it.
[scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString: &str1]; // Scan all the characters up to the whitespace and accumulate the characters into 'str1'
[scanner scanUpToCharactersFromSet:[NSCharacterSet alphanumericCharacterSet] intoString:nil]; // Scan up to the next alphanumeric character and discard the result.
[scanner scanUpToString:#"]" intoString:&str2]; // Scan up to the ']' character, accumulate the characters into 'str2'
// Log the output.
NSLog(#"First String: %#", str1);
NSLog(#"Second String: %#", str2);
Which puts the output into the console of:
2015-09-23 11:31:02.522 StringExtractor[46678:4289499] First String: string1
2015-09-23 11:31:02.522 StringExtractor[46678:4289499] Second String: string2

Find dynamically word in NSString

NSString * stringExample1=#"www.mysite.com/word-4-word-1-1-word-word-2-word-817061.html";
NSString * stringExample2=#"www.mysite.com/word-4-5-1-1-word-1-5-word-11706555.html";
I try to find - and . Inside of NSString.
NSRange range = [string rangeOfString:#"-"];
NSUInteger start = range.location;
NSUInteger end = start + range.length;
NSRange rangeDot= [string rangeOfString:#"."];
NSUInteger startt = rangeDot.location;
NSUInteger endt = startt + rangeDot.length;
But it's can't be successful. It's showing first place. How can I get 817061 and 11706555 inside of Nstring?
Thank you .
This will work for you,
NSArray *strArry=[stringExample1 componentsSeparatedByString:#"-"];
NSString *result =[strArry lastObject];
NSString *resultstring= [result stringByReplacingOccurrencesOfString:#".html" withString:#""];
Are you trying to find if it contains at least one of - or . ?
You can use -rangeOfCharacterFromSet:
NSCharacterSet *CharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"-."];
NSRange range = [YourString rangeOfCharacterFromSet:CharacterSet];
if (range.location == NSNotFound)
{
// no - or . in the string
}
else
{
// - or . are present
}
Try this simple Regular Expression.
NSString * stringExample1=#"www.mysite.com/word-4-word-1-1-word-word-2-word-84354354353.html";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(\\-\\d*\\.)"
options:0
error:&error];
NSRange range = [regex rangeOfFirstMatchInString:stringExample1
options:0
range:NSMakeRange(0, [stringExample1 length])];
range = NSMakeRange(range.location+1, range.length-2);
NSString *result = [stringExample1 substringWithRange:range];
NSLog(#"%#",result);
I think the best way to find the match is by using regulars expressions with NSRegularExpression.
NSString * stringEx=#"www.mysite.com/word-4-word-1-1-word-word-2-word-817061.html";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"-(\\d*).html$"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *matches = [regex matchesInString:stringEx options:NSMatchingReportCompletion range:NSMakeRange(0, [stringEx length])];
if ([matches count] > 0)
{
NSString* resultString = [stringEx substringWithRange:[matches[0] rangeAtIndex:1]];
NSLog(#"Matched: %#", resultString);
}
Make sure you use an extra \ escape character in the regex NSString whenever needed.
UPDATE
I did a test using the two different approaches (regex vs string splitting) with the code below:
NSDate *timeBefore = [NSDate date];
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"-(\\d*).html$"
options:NSRegularExpressionCaseInsensitive
error:&error];
for (int i = 0; i < 100000; i++)
{
NSArray *matches = [regex matchesInString:stringEx options:NSMatchingReportCompletion range:NSMakeRange(0, [stringEx length])];
if ([matches count] > 0)
{
NSString* resultString = [stringEx substringWithRange:[matches[0] rangeAtIndex:1]];
}
}
NSTimeInterval timeSpent = [timeBefore timeIntervalSinceNow];
NSLog(#"Time: %.5f", timeSpent*-1);
on the simulator the differences are not significant, but running on an iPhone 4 I got the following results:
2013-11-25 10:24:19.795 NotifApp[406:60b] Time: 11.45771 // string splitting
2013-11-25 10:25:10.451 NotifApp[412:60b] Time: 7.55713 // regex
so I guess the best approach depends on case to case.

Finding first letter in NSString and counting backwards

I'm new to IOS, and was looking for some guidance.
I have a long NSString that I'm parsing out. The beginning may have a few characters of garbage (can be any non-letter character) then 11 digits or spaces, then a single letter (A-Z). I need to get the location of the letter, and get the substring that is 11 characters behind the letter to 1 character behind the letter.
Can anyone give me some guidance on how to do that?
Example: '!!2553072 C'
and I want : '53072 '
You can accomplish this with the regex pattern: (.{11})\b[A-Z]\b
The (.{11}) will grab any 11 characters and the \b[A-Z]\b will look for a single character on a word boundary, meaning it will be surrounded by spaces or at the end of the string. If characters can follow the C in your example then remove the last \b. This can be accomplished in Objective-C like so:
NSError *error;
NSString *example = #"!!2553072 C";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(.{11})\\b[A-Z]\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
if(!regex)
{
//handle error
}
NSTextCheckingResult *match = [regex firstMatchInString:example
options:0
range:NSMakeRange(0, [example length])];
if(match)
{
NSLog(#"match: %#", [example substringWithRange:[match rangeAtIndex:1]]);
}
There may be a more elegant way to do this involving regular expressions or some Objective-C wizardry, but here's a straightforward solution (personally tested).
-(NSString *)getStringContent:(NSString *)input
{
NSString *substr = nil;
NSRange singleLetter = [input rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(singleLetter.location != NSNotFound)
{
NSInteger startIndex = singleLetter.location - 11;
NSRange substringRange = NSMakeRange(start, 11);
substr = [tester substringWithRange:substringRange];
}
return substr;
}
You can use NSCharacterSets to split up the string, then take the first remaining component (consisting of your garbage and digits) and get a substring of that. For example (not compiled, not tested):
- (NSString *)parseString:(NSString *)myString {
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
NSArray *components = [myString componentsSeparatedByCharactersInSet:letters];
assert(components.count > 0);
NSString *prefix = components[0]; // assuming relatively new Xcode
return [prefix substringFromIndex:(prefix.length - 11)];
}
//to get rid of all non-Digits in a NSString
NSString *customerphone = CustomerPhone.text;
int phonelength = [customerphone length];
NSRange customersearchRange = NSMakeRange(0, phonelength);
for (int i =0; i < phonelength;i++)
{
const unichar c = [customerphone characterAtIndex:i];
NSString* onechar = [NSString stringWithCharacters:&c length:1];
if(!isdigit(c))
{
customerphone = [customerphone stringByReplacingOccurrencesOfString:onechar withString:#"*" options:0 range:customersearchRange];
}
}
NSString *PhoneAllNumbers = [customerphone stringByReplacingOccurrencesOfString:#"*" withString:#"" options:0 range:customersearchRange];

Resources