0

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?

1 Answer 1

2

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"];
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry but can you explain exactly what you are doing?
Is there any way apart from using Regex to do this?
I have written a regex expression that matches an expression @[letters]#[letters]and then you can replace it with @" ".in the block i provided.
There are other ways such as find the @ sign in your string and taking it's position remove every character after it using substring method.
I found out a simpler solution, NSString *stringWithoutAnything = [string stringByReplacingOccurrencesOfRegex:[NSString stringWithFormat:@"%@ @%@",tagString,atString] withString:@""];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.