user798719
user798719

Reputation: 9869

How to erase part of an NSString with NSRegularExpression

I have a string: "My goal today is to work out 30 minutes [Last update: May 20, 2013 by Joe Smith] and eat healthy"

Could someone please craft a NSRegularExpression in Objective-C that extracts the substring:

[Last update: May 20, 2013 by Joe Smith]

I would like to basically erase the part of the string between square brackets [] so that my final string becomes: "My goal today is to work out 30 minutes and eat healthy"

Is the correct regular expression:

NSRegularExpression *regex = 
[NSRegularExpression regularExpressionWithPattern:@"[Last Update:*]" 
options:NSRegularExpressionCaseInsensitive error:&error];

I have seen online some regex that start with "\b", as well as others that escape square brackets: "\[Last update:*\]" --but with this one I get a compiler warning (but not error)

Upvotes: 0

Views: 138

Answers (2)

bdesham
bdesham

Reputation: 16089

It looks like you're trying to use * as what's called a shell glob: it means "match zero or more of any character". Shell globs are different from regular expressions, though, and in a regular-expression context, * actually means "match zero or more of the preceding atom". In your case, this would mean "match zero or more occurrences of :", which is not what you want.

What you want to do is

@"\\[Last Update:[^]]+\\] ?"

Note that we started with \\[. The "actual" regular expression here is \[; we had to add an extra backslash to escape the backslash because we're working within an Objective-C string. This \[ sequence matches a literal left square bracket. (Since that character has special significance in regular expressions, we need to escape it if there's going to be an actual [ in the text.) The same thing goes for the \\] at the end.

The sequence [^]]+ means "match any character other than ], and match as many as possible". Finally, the ? (a space followed by a question mark) at the end means that the regular expression will match a space, if one is there. This will prevent you from ending up with two spaces in a row when you remove the matched text. (Depending upon the format of your input, you may want to move the ? to the beginning of the expression instead.)

If you need more information about regular expressions in Objective-C, look at the NSRegularExpression documentation.

Upvotes: 3

NeverHopeless
NeverHopeless

Reputation: 11233

You can use this pattern:

\s*\[[^\]]+\]

It will return the data inside the bracket inclusive brackets and a space before them.

After that you have to follow these links to replace these string:

Example of NSRegularExpression (See example for NSTextCheckingResult)

Example for StringByReplacingOccurancesOfString or stringByReplacingCharactersInRange

Upvotes: 2

Related Questions