How to get everything within brackets in golang with regex

让人想犯罪 __ 提交于 2021-02-16 21:34:50

问题


I am trying to get everything within the outside brackets of the following sql statement in golang regular expressions.

Categories
(// = outside bracket
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)//=outside bracket

how would I use regex to only identify the outer brackets and return everything in between the outside brackets?


回答1:


All you need is to find the first (, then match any characters up to the last ) with

`(?s)\((.*)\)`

Details:

  • (?s) - allow . to match any character, including a newline
  • \( - a literal ( char
  • (.*) - Submatch 1 capturing any zero or more characters
  • \) - a literal ) symbol.

See the Go demo:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := `Categories
(// = outside bracket
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)//=outside bracket`
    re := regexp.MustCompile(`(?s)\((.*)\)`)

    m := re.FindAllStringSubmatch(s,-1)
    fmt.Printf("Capture value: %s", m[0][1])
}


来源:https://stackoverflow.com/questions/39488210/how-to-get-everything-within-brackets-in-golang-with-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!