dqyuipw44576
dqyuipw44576
2019-07-04 05:18
浏览 207
已采纳

如何在Golang中的正则表达式中的第一个匹配项之前插入子字符串?

I have a regex as following (ORDER\s+BY)|(LIMIT)|$. I want to insert a substring before the first match of the regex. I am looking for a pure regexp solution in Golang not finding the index and then adding a substring. Since Golang only has regexp.ReplaceAll func which replaces all the matches, not the first one.

exp := regexp.MustCompile(`(ORDER\s+BY)|(LIMIT)|$`)
fmt.Println(exp.ReplaceAllString(str, "..."))

Example

Input: abcd ORDER BY LIMIT substring=GROUP BY

Expected output: abcd GROUP BY ORDER BY LIMIT

Input: abcd LIMIT

Expected output: abcd GROUP BY LIMIT

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongpu1331
    dongpu1331 2019-07-04 05:31
    已采纳

    You may use

    str := "abcd ORDER BY LIMIT"
    exp := regexp.MustCompile(`^(.*?)(ORDER\s+BY|LIMIT|$)`)
    fmt.Println(exp.ReplaceAllString(str, "${1}GROUP BY ${2}"))
    

    If there can be line breaks before the pattern use (?s) in front: (?s)^(.*?)(ORDER\s+BY|LIMIT|$).

    See the Go demo and the regex graph:

    enter image description here

    Details

    • ^ - start of string
    • (.*?) - Group 1 (${1}): any 0+ chars, as few as possible
    • (ORDER\s+BY|LIMIT|$) - Group 2 (${2}): any of the three alternatives, whichever comes first:
      • ORDER\s+BY - ORDER, 1+ whitespaces, BY
      • LIMIT - a LIMIT substring
      • $ - end of string.
    点赞 评论
  • douqiangbei50208
    douqiangbei50208 2019-07-04 05:32

    My guess is that this expression might work here:

    (ORDER\s+BY\s+LIMIT|LIMIT)$
    

    Demo

    Test

    package main
    
    import (
        "regexp"
        "fmt"
    )
    
    func main() {
        var re = regexp.MustCompile(`(?m)(ORDER\s+BY\s+LIMIT|LIMIT)$`)
        var str = `abcd ORDER BY LIMIT
    abcd LIMIT`
        var substitution = "GROUP BY $1"
    
        fmt.Println(re.ReplaceAllString(str, substitution))
    }
    
    点赞 评论

相关推荐