问题描述
在Go语言中进行开发时,给定一个字符串如何提取“%”之间的某些元素,然后将最后一个“%”右侧的子字符串捕获为一个元素?还会如何检查是否可以对给定的字符串执行Regex操作?
Ex:
This is %stackoverFlow% and it's a %Phenomenal% "$ resource
$ presentations and got credit for it. I brought this up to $
$ were She looked at me and said. She looked at me and said,$
现在我想得到
element 1: StackoverFlow
element 2: Phenomenal
element 3: "$ resource
$ presentations and got credit for it. I brought this up to $
$ were She looked at me and said. She looked at me and said,$
到目前为止我已经完成的工作,该表达式将捕获“%”中的两个元素
\%(.*?)\%
但是我不知道如何继续在同一个Regex表达式中捕获元素右侧的所有内容作为单个捕获?
#2)我们如何创建条件来确定String包含具有%content%的子字符串? 例如
This is StackOverFlow
此字符串不包含“%”,其间没有内容,是否可以确定正则表达式是否可以在上面的此字符串上使用?
解决方法
以下模式似乎有效:
%(.*?)%[^%]*%(.*?)%\s+(.*)
Demo
说明:
%(.*?)% match and capture first term %...% in $1
[^%]* consume all content up until hitting the next
%(.*?)% %...% term in $2
\s+ match one or more whitespace characters
(.*) match and capture the remaining content in $3
请注意,我正在为此规则表达式使用点所有模式。如果没有可用的点所有模式,则将([\s\S]*)
用作上述正则表达式模式的最后一个组成部分。