Replace occurences of string that contains any number - ios

Say I have a string that contains a control code "\f3" (yes it is RTF). I want to replace that control code with another string. At the moment I am using [mutableString replaceOccurrencesOfString:#"\f3" withString:#"replacement string" options:0 range:NSMakeRange(0, [mutableString length])];
This works fine, however sometimes the code can be "\f4" or even "\f12" for example. How do I replace these strings? I could use replaceOccurrencesOfString for each, but the better way to do it is using wildcards, as it could be any number.

Regular expressions would do it.
Take a look at NSRegularExpression (iOS >= 4) and this page for how regular expressions work.
You will want something like:
// Create your expression
NSError *error = nil;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:#"\\b\f[0-9]*\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
// Replace the matches
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"replacement string"];
WARNING : I've not tested my regaular expression and I'm not that great at getting them right first time; I just know that regular expressions are the way forward for you and it has to look something like that ;)

Related

RegEx - Detect specific strings before anything that isn't those strings [duplicate]

I have an NSString, let's say "H,L,K,P" how can I detect a specific character than then a wild-car character... for example, checking for ",*" would return ",L" ",K" and ",P" because they all have the specific "," and then they all have a character after them. Then I want to replace that string with itself plus a "period" appended to it.
So "H,L,K,P" would become "H,L.,K.,P."
Use a regular expression. The search pattern would be:
,(.)
the replacement pattern would be:
,$1.
Sample code:
NSString *string = #"H,L,K,P";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#",(.)"
options:0
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#",$1."];

NSMutableString replaceOccurrencesOfString replacing whole words

Is there a way to use replaceOccurrencesOfString (from NSMutableString) to replace whole words?
For example, if I want to replace all occurrences of a fraction in a string, like "1/2", I'd like that to match only that specific fraction. So if I had "11/2", I would not want that to match my "1/2" rule.
I've been trying to look for answers to this already, but I am having no luck.
You could use word boundaries \b with Regex. This example matches the "1/2" at the start and the end of the example string, but neither of the middle options
// Create your expression
NSString *string = #"1/2 of the 11/2 objects were 1/2ed in (1/2)";
NSError *error = nil;
NSRegularExpression *regex =
[NSRegularExpression
regularExpressionWithPattern:#"\\b1/2\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
// Replace the matches
NSString *modifiedString =
[regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"HALF USED TO BE HERE"];

Regex issue in IOS Program

I am trying to get the following regex to work on ios in order to make sure the user is only inputting numbers and a dot. I am not able to get number of matches to be above 0. I have also tried NSRange one as well and that will give me 0 no matter what as well, so my regex is not working, even thought I am pretty sure it should with what I have there. Any suggestions.
The Code I wrote is here with errorRegex is defined in the .h file and regError is defined as well.
errorRegex = [NSRegularExpression regularExpressionWithPattern:#"[^0-9.]*"
options: NSRegularExpressionCaseInsensitive error:&regError];
NSUInteger rangeOfFirstMatch = [errorRegex numberOfMatchesInString:servAmount1TF.text
options:0 range:NSMakeRange(0, [servAmount1TF.text length])];
Why not use stock-standard c's regex.h ?
See an example here:
http://cboard.cprogramming.com/c-programming/117525-regex-h-extracting-matches.html
And more information here:
https://stackoverflow.com/a/422159/1208218
errorRegex is of type NSRegularExpression, but the error is of type UIButtonContent. This has all the halmarks of a memory error. Something in your code not going though a proper retain/release cycle.
I got a unit test to work with the expression #"[^0-9.]+"
- (void)testRE
{
NSError *regError = nil;
NSRegularExpression *errorRegex;
NSString *string;
NSUInteger count;
errorRegex = [NSRegularExpression regularExpressionWithPattern:#"[^0-9.]+"
options: NSRegularExpressionCaseInsensitive
error:&regError];
STAssertNil(regError, nil);
string = #"00.0";
count = [errorRegex numberOfMatchesInString:string
options:0
range:NSMakeRange(0, [string length])];
STAssertEquals(count, 0U, nil);
string = #"00A00";
count = [errorRegex numberOfMatchesInString:string
options:0
range:NSMakeRange(0, [string length])];
STAssertEquals(count, 1U, nil);
}
NSRegularExpression *errorCheckRegEx = [[NSRegularExpression alloc] initWithPattern:#"\\b^([0-9]+(\\.)?[0-9]*)$|^([0-9]*(\\.)?[0-9]+)$|^[0-9]*$|^([0-9]*(\\/)?[0-9]*)$\\b" options:NSRegularExpressionCaseInsensitive error:nil];
[match setArray: [errorCheckRegEx matchesInString:servAmount1TF.text options:0 range:NSMakeRange(0, [servAmount1TF.text length])]];
I figured out what I needed to do when I could finally get back to it so if anyone was interested this is what I came up with. The \b is just what ios uses in their regexp which is kind of dumb, but it will not work without that so I leave it there when it doesn't feel natural to do especially after ruby's example. This regular expression will get fractions, decimals -> .3; 2.3; 2; and does it from the front to end of the line. What I think might have been happening was the fact that I was not using the \b and also not matching correctly, which is the second line. Either way it works great now. Thanks for the help.

Excluding strings from one string using Regex in iOS

I want to do pretty much the same as in Excluding strings using regex but I want to do it iOS using Regex. So I basically I want to find matches in a string and then remove them from the string so if I have a string like this, Hello #world #something I want to find #world & #something and then remove them from the string so it just becomes Hello. I already have this expression that removes #world and something but not the #, #[\\p{Letter}]+|[^#]+$ I solved the # problem by doing this
NSString *stringWithoutAt = [input stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"#%#",atString] withString:#""];
NSString *stringWithoutTag = [input stringByReplacingOccurrencesOfString:tagString withString:#""];
So for the first one I end up with Hello #world and the second one Hello #something. But is there a way of using Regex or something else to remove both the #world and the #something at the same time?
You can use regex in iPhone in two ways:-
1>Using RegExKitLIte as framework see the tutorial
2>Using NSRegularExpression & NSTextCheckingResult
NSStirng *string=#"Your String";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"#[a-z]*#[a-z]*" options:NSRegularExpressionCaseInsensitive error:&error];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop)
{
// your statement if it matches
}];
Here any expression after# and expression after # is being concatenated
and in the statement you can replace it by space to get your expression
if u simply want modified string do this :-
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0
range:NSMakeRange(0, [string length]) withTemplate:#"$2$1"];

NSRegularExpression, specify case-sensitive match?

Is there a way using NSRegularExpression to specify that you want to do a case-sensitive search? I am trying to match the upper-case TAG "ACL" in the text below. The pattern I am using is simply:
// Pattern
[A-Z]+
// SearchText
<td align=\"left\" nowrap><font face=\"courier, monospace\" size=\"-1\">ACL*</font></td>
// Code:
NSString *textBuffer = #"<td align=\"left\" nowrap><font face=\"courier, monospace\" size=\"-1\">ACL*</font></td>";
NSString *pattern = #"([A-Z]+)";
NSRegularExpression *regExp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSTextCheckingResult *result = [regExp firstMatchInString:textBuffer options:0 range:NSMakeRange(0, [textBuffer length])];
NSLog(#"OBJECT CLASS: %#", [textBuffer substringWithRange:[result range]]);
Output: (with case-Insensative I am getting the first "td" as expected, when what I really want is "ACL"
I know that NSRegularExpressionCaseInsensitive is wrong, I was hoping there would be a NSRegularExpressionCaseSensitive. Also there is a flagOption ?(i) that also specifies a case-insensitive search but again nothing for case-sensative. What am I missing?
Case sensitive is the default. Dont put the insensitive flag in there.

Resources