提取一个完全可选模式中的可选项目名称

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

Extracting an optional project name in a fully optional pattern

问题

  1. 如果字符串中存在 "projects",则捕获 "x" 并存储在名为 "project_name" 的组中。
  2. 如果字符串中不存在 "projects",则捕获整个字符串。

使用的正则表达式是 "\S*(projects\/(?<project_name>\w+))?"

但是 "x" 没有被捕获并存储在一个捕获组中。不确定您的正则表达式有什么问题。

英文:

I have this string "https://url/projects/x/flow/" and i want:

  1. if projects is existing in the string, capture x in a group named project_name
  2. if projects not existing in the string, then capture the whole string

The regex i am using is "\S*(projects\/(?<project_name>\w+))?"

But x is not captured and stored in a capturing group. Not sure what is wrong with my regex.
Your help is appreciated

答案1

得分: 1

你可以使用以下正则表达式:

^(?:\S*?(projects\/(?<project_name>\w+)))?.*

查看正则表达式演示

详细信息

  • ^ - 字符串的开始
  • (?:\S*?(projects\/(?<project_name>\w+)))? - 一个可选的非捕获组:
    • \S*? - 任何零个或多个非空白字符,尽可能少
    • (projects\/(?<project_name>\w+)) - 第1组:projects/ + 之后一个或多个单词字符,捕获到 "project_name" 组
  • .* - 字符串的其余部分。
英文:

You can use

^(?:\S*?(projects\/(?&lt;project_name&gt;\w+)))?.*

See the regex demo.

Details:

  • ^ - start of string
  • (?:\S*?(projects\/(?&lt;project_name&gt;\w+)))? - an optional non-capturing group:
    • \S*? - any zero or more non-whitespace chars, as few as possible
    • (projects\/(?&lt;project_name&gt;\w+)) - Group 1: projects/ + one or more word chars after it captured into "project_name" group
  • .* - the rest of the string.

huangapple
  • 本文由 发表于 2023年7月6日 17:19:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627317.html
匿名

发表评论

匿名网友

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

确定