tags:

views:

67

answers:

4

I am using RegexKitLite in an iPhone project and want to use regex to find words that start with the @-sign. For instance, "@home @chores", when searched, would return both words.

The regex string I am using is "(?m-s:@.*\\s*)". When I use this, though, I get a crash. When I use the same thing, but with a # instead of @, it works just fine: "(?m-s:#.*\\s*)". WTF?

I would much appreciate it if someone with a better understanding of regular expressions could help me on this. The tutorials I have seen so far have been near incomprehensible to me.

A: 

Why not simply use /\b@\w+/

Manu
That doesn't work.
Jonathan Sterling
A: 

Have you tried something like that:

NSString *search = @"This is my @home string with @some tokens to be @found";
NSString *regex = @"\\b@(\\w+)";
NSArray  *matches = NULL;

matches = [search componentsMatchedByRegex:regex];
// now matches should have { @"home", @"some", @"found" } values

I haven't tested that but should work.

RaYell
Nope, that doesn't work. NSLog([matches description]); shows nothing.
Jonathan Sterling
Can you try escaping @ with double backslashes as well?
RaYell
+1  A: 

I did a modification of Manu's idea, just switching the location of the @ in the regex.

/(@\b\w+)/

I tested it on a string with '@foo @bar @baz @lol' and it seemed to do what you're looking for in matching on the words and capturing them with the parens.

Kyle Walsh
You’re a genius! Thanks a lot!Question: where can I find a really good regex tutorial? I never understand how you people come up with these regexes. Thanks again!
Jonathan Sterling
A: 

This may sound too simple, but have you tried changing @ to \@ or \\@

R. Bemrose
Haha, that's the first thing I thought. Then I figured "no way, too simple" and deleted it...but since you're suggesting it too I don't feel as silly. Self-conciousness ftw.
Kyle Walsh
I know nothing about how RegEx's work on the iPhone, but if there's a problem with just one character in a RegEx, escaping it is the first thing I try. ;)
R. Bemrose
Yeah, I tried those, but it doesn't work for some reason…
Jonathan Sterling