Golang正则表达式在字符串中存在可选部分时无法匹配。

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

Golang Regex not matching the optional part even when it is present in the string

问题

我正在尝试解析一些命令的输出,我想检查命令是否有错误,所以我查找字符串**Apply Error**。如果没有错误,之前提到的字符串就不存在。我的正则表达式匹配模式是(?s)Ran Apply.+?(\*\*Apply Error\*\*)?。我是在Golang中进行这个操作的。

即使输出中存在字符串** Apply Error**,这个正则表达式也不起作用,如果我删除正则表达式中的最后一个?,它就能按预期工作。它捕获了两个组,第二个组是可选的部分。

示例:
情况1:当字符串**Apply Error**存在时

Ran Apply for dir: `some random path/something/something`

`**Apply Error**`

输出:匹配**Apply Error**并将其捕获为一个组

情况2:当**Apply Error**不存在时

Ran Apply for dir: `some random path/something/something`
some random text

输出:按原样匹配所有内容

演示:https://regex101.com/r/Um3CNc/1
在演示中,即使存在** Apply Error**,它也无法匹配。

如何匹配可选部分?

英文:

I am trying to parse some output from a command, I want to check if the command had an error in it, so I look for the string **Apply Error**. If there is no error present the previously mentioned string is absent. My regex to match that is (?s)Ran Apply.+?(\*\*Apply Error\*\*)?. I am doing this in Golang

This regex does not work even when the string ** Apply Error** is present in the output, if I remove the last ? in my regex it works as expected. It captures 2 groups with the second being the optional part.

Examples:
Case - 1 when the string **Apply Error** is present

Ran Apply for dir: `some random path/something/something`

`**Apply Error**`

Output: Match **Apply Error** and capture it as a group

Case - 2
When **Apply Error** is not present

Ran Apply for dir: `some random path/something/something`
some random text

Output: Match everything as is

Demo: https://regex101.com/r/Um3CNc/1
In the demo even though ** Apply Error** is present it does not match it

How can I match the optional part?

答案1

得分: 2

你可以使用以下正则表达式进行匹配:

(?s)Ran Apply\b(?:.+?(\*\*Apply Error\*\*)|.*) 

解释:

  • (?s) 内联修饰符,使点号匹配换行符
  • Ran Apply\b 匹配字面上的 "Ran Apply" 后面跟着一个单词边界
  • (?: 非捕获组
  • .+?(\*\*Apply Error\*\*) 匹配1个或多个字符,尽可能少地匹配,并在第1组中捕获 **Apply Error**
    • | 或者
    • .* 匹配剩余的文本
  • ) 结束非捕获组

查看带有 "Apply Error" 的正则表达式演示链接,以及不带 "Apply Error" 的正则表达式演示链接

英文:

You can use

(?s)Ran Apply\b(?:.+?(\*\*Apply Error\*\*)|.*)

Explanation

  • (?s) Inline modifier to have the dot match a newline
  • Ran Apply\b Match literally followed by a word boundary
  • (?: Non capture group
  • .+?(\*\*Apply Error\*\*) Match 1+ chars, as few as possible and capture **Apply Error** in group 1
    • | Or
    • .* Match the rest of the text
  • ) Close non capture group

See a regex demo with Apply Error present and without Apply Error present.

huangapple
  • 本文由 发表于 2022年7月2日 10:10:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/72836006.html
匿名

发表评论

匿名网友

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

确定