Extract values between parenthesis from NSString

后端 未结 4 860
一整个雨季
一整个雨季 2021-02-09 21:56

I have an NSString that will be something like \"xxxx (yyyyy)\" where x and y can be any character. I\'d like to extract just the y from inside the parenthesis. I managed to ext

相关标签:
4条回答
  • 2021-02-09 22:17

    Easiest way would be to use RegExKit:

    http://regexkit.sourceforge.net/

    Then you'd do something like:

    [@"xxxx(yyyyy)" getCapturesWithRegexAndReferences:@"\\((.*)\\)",@"$1", &extractedString,nil];
    

    and extractedString would contain whatever was in parenthesis.

    0 讨论(0)
  • 2021-02-09 22:23

    Scan up to the ‘(’, then scan it, then scan up to the ')'. The result of the last scan is yyyy.

    0 讨论(0)
  • 2021-02-09 22:31

    you might have a look at PKTokenizer in ParseKit:

    http://parsekit.com

    0 讨论(0)
  • 2021-02-09 22:36

    Just to be complete:

    If you are absolutely sure of the format of your output you can use the array methods:

    NSString *inputString; // this is in the form "xxxx(yyyy)"
    
    NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:@"()"];
    NSArray *splitString = [inputString componentsSeparatedByCharactersInSet:delimiters];
    
    NSString *xString = [splitString objectAtIndex:0];
    NSString *yString = [splitString objectAtIndex:1];
    

    Of course, you need to be sure that the delimiting characters don’t exist in the inputString

    0 讨论(0)
提交回复
热议问题