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

如何在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 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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动