Search code examples
regexios7nsstring

Regular expression for extracting excerpt from long String


I want to extract excerpt from a long string using Regular expression

Example string: "" Is it possible that Germany, which beat Argentina 1-0 today to win the World Cup, that will end up as a loser in terms of economic growth? ""

String to search: " that "

Expected result from regex

" possible that Germany "

" rd Cup, that will end "

I want to search the desired text from the string with -9 and +9 characters from the forward and the backward of the occurence of the searched string. Search string can occur multiple times within the given string.

I am working on an iOS app using iOS 7.

I have so far created this expression with my little knowledge about reguler expressions but not able to get desired result from that

 " (.){0,9} (that) {0,9} "

Solution

  • Remove the spaces in your regex. If you want to capture the matched ones. Then enclose the pattern within capturing groups (ie, ()),

    .{9}that.{9}
    

    OR

    (?:.{9}|.{0,9})that(?:.{9}|.{0,9})
    

    DEMO

    Make the preceding and following characters as optional to match the line which looks like that will change history