Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Regex for extracting words between parenthesis

Tags:

regex

swift

Hello i wanna extract the text between ().

For example :

(some text) some other text -> some text
(some) some other text      -> some
(12345)  some other text    -> 12345

the maximum length of the string between parenthesis should be 10 characters.

(TooLongStri) -> nothing matched because 11 characters

what i have currently is :

let regex   = try! NSRegularExpression(pattern: "\\(\\w+\\)", options: [])

regex.enumerateMatchesInString(text, options: [], range: NSMakeRange(0, (text as NSString).length))
{
    (result, _, _) in
        let match = (text as NSString).substringWithRange(result!.range)

        if (match.characters.count <= 10)
        {
            print(match)
        }
}

which works nicely but the matches are :

(some text) some other text -> (some text)
(some) some other text      -> (some)
(12345)  some other text    -> (12345)

and doesn't match <=10 because () are counted also.

How can i change the code above to solve that? I would like also to remove the if (match.characters.count <= 10)by extending the regex to hold the length info.

like image 867
fizampou Avatar asked Sep 10 '25 22:09

fizampou


1 Answers

You can use

"(?<=\\()[^()]{1,10}(?=\\))"

See the regex demo

The pattern:

  • (?<=\\() - asserts the presence of a ( before the current position and fails the match if there is none
  • [^()]{1,10} - matches 1 to 10 characters other than ( and ) (replace [^()] with \w if you need to only match alphanumeric / underscore characters)
  • (?=\\)) - checks if there is a literal ) after the current position, and fail the match if there is none.

If you can adjust your code to get the value at Range 1 (capture group) you can use a simpler regex:

"\\(([^()]{1,10})\\)"

See the regex demo. The value you need is inside Capture group 1.

like image 199
Wiktor Stribiżew Avatar answered Sep 13 '25 12:09

Wiktor Stribiżew