Swift Regex for extracting words between parenthesis

前端 未结 2 1600
难免孤独
难免孤独 2020-12-21 12:11

Hello i wanna extract the text between ().

For example :

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


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-21 12:36

    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.

提交回复
热议问题