正则表达式在Golang中如何匹配花括号内最后一个模式?

huangapple go评论75阅读模式
英文:

regex golang last match of a pattern inside curly braces

问题

我有以下字符串,我想匹配最后一个大括号(包括括号内的内容),即输出应为{ahhh}

abc {popo}/popo/{ahhh}

Golang不支持负向先行断言,我尝试了以下模式但没有成功:

{.+?}$
{.+?}([^/])

非常感谢您的帮助。谢谢。

英文:

I have the following string, and I want to match the contents of the last curly brace (inclusive), i.e. the output should be {ahhh}.

abc {popo}/popo/{ahhh}

Golang does not support negative lookahead, and I have tried the following patterns but it has not worked

{.+?}$
{.+?}([^/])

Any help would be much appreciated. Thank you.

答案1

得分: 2

你可以匹配从开头到字符串末尾的闭合大括号:

\{[^{}]*}$

正则表达式演示

或者你可以匹配整行,并捕获最后一个大括号后面的任意字符(除了斜杠)直到字符串末尾。

.*(\{[^{}]*})[^/]*$

正则表达式演示

英文:

You could match from an opening till closing curly at the end of the string:

\{[^{}]*}$

Regex demo

Or you could match the whole line, and then capture the last occurrence of the curly's followed by matching any char except / till the end of the string.

.*(\{[^{}]*})[^/]*$

Regex demo

huangapple
  • 本文由 发表于 2022年8月12日 18:46:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/73332952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定