Swift Regex for extracting words between parenthesis

前端 未结 2 1599
难免孤独
难免孤独 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:18

    This will work

    \((?=.{0,10}\)).+?\)
    

    Regex Demo

    This will also work

    \((?=.{0,10}\))([^)]+)\)
    

    Regex Demo

    Regex Breakdown

    \( #Match the bracket literally
    (?=.{0,10}\)) #Lookahead to check there are between 0 to 10 characters till we encounter another )
    ([^)]+) #Match anything except )
    \) #Match ) literally
    
    0 讨论(0)
  • 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.

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