5

I have a string like @"random ++qwerty/asdf" and I want to fish out the qwerty part. The "random ++" and "/asdf" will always be the same. How would I go about doing this using regular expressions? I'm confused as to how they work.

9
  • Here is a good resource. What have you tried? Commented Apr 24, 2013 at 23:59
  • i will take a look here, hte nsregularexpression documentation is really confusing Commented Apr 25, 2013 at 0:00
  • Admittedly, regular expressions are something that isn't intuitive enough to be easily learned from reading a documentation. However, if you take some time and read through the linked tutorial (at least the first few chapters) you'll get a really good grasp on it - and it's definitely valuable knowledge. Commented Apr 25, 2013 at 0:04
  • 4
    You could just use -substringWithRange:. Commented Apr 25, 2013 at 0:23
  • 1
    BOOL isRightFormat = [string rangeOfString: @"random ++"].location == 0; Commented Apr 25, 2013 at 0:33

1 Answer 1

15

Problem Solved !!

This code give exactly what you want,

NSString *yourString = @"random ++qwerty/asdf random ++derty/asdf random ++noty/asdf";
NSError *error = NULL;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"random \\+\\+(\\w+)/asdf" options:NSRegularExpressionCaseInsensitive error:&error];


[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){

    // detect
    NSString *insideString = [yourString substringWithRange:[match rangeAtIndex:1]];

    //print
    NSLog(@"%@",insideString);

}];


Output:
qwerty
derty
noty

Sign up to request clarification or add additional context in comments.

1 Comment

With so many resources available on regex usage, it still helps a lot to have concrete examples like this about specific types of matches! Thanks!

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.