如何在Golang的正则表达式中添加if条件,只有在组存在的情况下才匹配。

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

How to add an if condition to regex on Golang to match only if the group exists in Golang

问题

我正在测试两个字符串,并希望根据条件应用一个通用的正则表达式模式,如果存在一个组,则应用正则表达式模式,否则应用另一个模式,但是在正则表达式在线编辑器中,似乎无法识别?=()来添加if else条件。

我有以下两个测试字符串:

/public/weltweit/nfsk/2022/05/18/668e9f57-30be-40b6-bc85-5bf66671e41d/668e9f57-30be-40b6-bc85-5bf66671e41d_AVC-270.mp4

使用^\/(\bpublic\b[\/])*(.+[a-z]{1,}.*[\/|_]+)+.*?$进行提取的预期结果是

weltweit/nfsk/2022/05/18/668e9f57-30be-40b6-bc85-5bf66671e41d/668e9f57-30be-40b6-bc85-5bf66671e41d_

这是预期的结果,但对于另一个测试字符串:

/medp/ondemand/weltweit/fsk0/258/2580407/2580407_40256616.mp4 使用相同的正则表达式,我得到了medp/ondemand/weltweit/fsk0/258/2580407/2580407_

我期望提取的结果是**medp/ondemand/weltweit/fsk0/258/2580407/** 我想在组(\bpublic\b[\/])中添加一个if条件,如果该组存在,则选择下划线**_**,否则选择斜杠**/**

感谢任何指导。谢谢!

英文:

I am testing two strings and want a common regex to be applied based on the condition if one group exists then apply the Regex Pattern, else other Pattern, but some reason on Regex online editor it seems that the ?=() is not recognized to add if else condition.

I have the following 2 test strings:

/public/weltweit/nfsk/2022/05/18/668e9f57-30be-40b6-bc85-5bf66671e41d/668e9f57-30be-40b6-bc85-5bf66671e41d_AVC-270.mp4

Expected extraction using ^\/(\bpublic\b[\/])*(.+[a-z]{1,}.*[\/|_]+)+.*?$ is

weltweit/nfsk/2022/05/18/668e9f57-30be-40b6-bc85-5bf66671e41d/668e9f57-30be-40b6-bc85-5bf66671e41d_

which is expected but for the other test string :

/medp/ondemand/weltweit/fsk0/258/2580407/2580407_40256616.mp4 with same Regex I get medp/ondemand/weltweit/fsk0/258/2580407/2580407_

My expected extraction is **medp/ondemand/weltweit/fsk0/258/2580407/**
I want to add a if condition to a group (\bpublic\b[\/]) so that an underscore **_**is chosen if the group exists; otherwise a slash **/**

Any pointers is appreciated.

Thank you!

答案1

得分: 1

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

^/(?:public/(.*_)|(.*/))

可以在正则表达式演示中查看结果,结果将出现在第一组或第二组中。

详细说明

  • ^ - 字符串的开头
  • / - 斜杠
  • (?: - 开始一个非捕获组:
    • public/ - 固定字符串
    • (.*_) - 第一组:任意数量的非换行字符,尽可能多地匹配,然后是一个下划线字符
    • | - 或者
    • (.*/) - 第二组:任意数量的非换行字符,尽可能多地匹配,然后是一个斜杠字符
  • ) - 组的结束。
英文:

You can use

^/(?:public/(.*_)|(.*/))

See the regex demo. The result is either in Group 1 or Group 2.

Details:

  • ^ - start of string
  • / - a slash
  • (?: - start of a non-capturing group:
    • public/ - a fixed string
    • (.*_) - Group 1: any zero or more chars other than line break chars as many as possible and then a _ char
    • | - or
    • (.*/) - Group 2: any zero or more chars other than line break chars as many as possible and then a / char
  • ) - end of the group.

huangapple
  • 本文由 发表于 2022年6月21日 19:34:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/72700054.html
匿名

发表评论

匿名网友

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

确定