英文:
Extracting an optional project name in a fully optional pattern
问题
- 如果字符串中存在 "projects",则捕获 "x" 并存储在名为 "project_name" 的组中。
- 如果字符串中不存在 "projects",则捕获整个字符串。
使用的正则表达式是 "\S*(projects\/(?<project_name>\w+))?"
但是 "x" 没有被捕获并存储在一个捕获组中。不确定您的正则表达式有什么问题。
英文:
I have this string "https://url/projects/x/flow/"
and i want:
- if projects is existing in the string, capture x in a group named project_name
- 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\/(?<project_name>\w+)))?.*
See the regex demo.
Details:
^
- start of string(?:\S*?(projects\/(?<project_name>\w+)))?
- an optional non-capturing group:\S*?
- any zero or more non-whitespace chars, as few as possible(projects\/(?<project_name>\w+))
- Group 1:projects/
+ one or more word chars after it captured into "project_name" group
.*
- the rest of the string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论