regex - 尝试编写与给定字符串匹配的正则表达式并将其分成组
问题描述
我想编写一个从给定字符串中提取这些细节的正则表达式
第 1 组:动作(恒定且应匹配“/search”)
第 2 组:命令
第三组:查询
第 4 组:流派(如果可能,带或不带“-”通过)
条件一:
Matches “/search music heal the world -pop” or “/search movies avengers -action” into four (4) groups.
Group 1 | Group 2 | Group 3 | Group 4
--------------------------------------------
/search | music | heal the world | pop
/search | movies | avengers | action
条件二:
Matches “/search music heal the world” or “/search movies avengers” into three (3) groups.
Group 1 | Group 2 | Group 3
------------------------------
/search | music | heal the world
/search | movies | avengers
条件 3:
Matches “/search music” or “/search movies” into two (2) groups.
Group 1 | Group 2
----------------
/search | music
/search | movies
条件 4:
Matches “/search” into a group.
Group 1
--------
/search
当谈到正则表达式时,我仍然是一个新手,完成这件事给我带来了一些麻烦。我想出了这个(\/search)\s([^\s]+)\s(.+)\s(.+)
,但它只匹配/search music heal the world pop
或/search movies avengers action
将它们分成四 (4) 组,但不匹配其他条件。
解决方案
我使用命名组和非捕获组以获得更清晰的结果
^(?<Action>\/search)(?:\s+(?<Command>\w+)(?:\s+(?<Query>(?:\w|\s)+))?)?(?:\s+-(?<Genre>\w+))?$
推荐阅读
- java - 进程虚拟内存大小作为常驻内存大小的合适比例是多少
- reactjs - 收到警告错误:验证 DOM 嵌套后代
- json - 我可以为 Parse Server 创建一个配置文件吗?
- python - TypeError: x 必须是 GEKKO 参数、变量或表达式的 python 列表
- grpc - 双向流的 gRPC onComplete
- javascript - 如何隐藏同一个类的多个元素的父级?
- javascript - 这个疯狂的 jQuery 选择器相当于什么?
- mongodb - 如何在MongoDB中获取没有父母的文件
- c# - PHP 到 C# 加密消息 - 解密麻烦
- elasticsearch - elastic search high level rest client v.7.5 java如何初始化