【问题标题】:Swift Regex for extracting words between parenthesisSwift Regex 用于提取括号之间的单词
【发布时间】:2016-04-29 14:48:04
【问题描述】:

您好,我想提取 () 之间的文本。

例如:

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

括号之间的字符串的最大长度应为 10 个字符。

(TooLongStri) -> nothing matched because 11 characters

我目前拥有的是:

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)
        }
}

效果很好,但匹配的是:

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

不匹配

如何更改上面的代码来解决这个问题?我还想通过扩展正则表达式来删除if (match.characters.count &lt;= 10)以保存长度信息。

【问题讨论】:

    标签: regex swift


    【解决方案1】:

    你可以使用

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

    regex demo

    图案:

    • (?&lt;=\\() - 在当前位置之前断言存在(,如果没有则匹配失败
    • [^()]{1,10} - 匹配除 () 之外的 1 到 10 个字符(如果您只需要匹配字母数字/下划线字符,请将 [^()] 替换为 \w
    • (?=\\)) - 检查当前位置之后是否有文字 ),如果没有则匹配失败。

    如果您可以调整代码以获取 Range 1(捕获组)的值,则可以使用更简单的正则表达式:

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

    请参阅regex demo。您需要的值在 Capture 组 1 中。

    【讨论】:

      【解决方案2】:

      这会起作用

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

      Regex Demo

      这也行

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

      Regex Demo

      正则表达式分解

      \( #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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多