dongxinm279890 2015-07-24 10:03
浏览 298
已采纳

Go lang从字符串中获取匹配的子字符串

I'm trying to extract all words from a string which are between quotes.

Here's my current code:

func StrExtract(word string) []string {
  r, _ := regexp.Compile(`".*"`)
  result := r.FindAllString(word, -1)
  RemoveDuplicates(&result)
  return (result)
}

Test the code here

With an input like:

`Hi guys, this is a "test" and a "demo" ok?`

I get the output:

["test" and a "demo"]

But I'd like to get:

[test demo]

Please help me fix this, or suggest better alternatives.

  • 写回答

2条回答 默认 最新

  • dqenv99518 2015-07-24 10:06
    关注

    You can just add a lazy quantifier .*?, ".*?" being the regex, if you want to keep it simple. The reason you are getting "test" and a "demo" is because just .* is greedy and matches as much text as possible (therefore, it actually matches the " before test and after demo, ignoring the fact that there are other quotes in between).

    Normally a better but in some ways slightly more complicated way to do this is using character classes "[^"]*", disabling matching quotes in between. This can also cause some other behaviors like including newlines (in which case you can also disable them [^" ], or perhaps you actually want such a case)

    Since you want to also not have the quotes some additional things need to be done. You can do that with either lookarounds: (?<=")[^"]*(?="), or with capture groups: "(.*?)" and "([^"]*)". If you choose the capture group route, you have to use the capture group, not whole matches.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100