首页 > 解决方案 > 尝试编写与给定字符串匹配的正则表达式并将其分成组

问题描述

我想编写一个从给定字符串中提取这些细节的正则表达式

第 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) 组,但不匹配其他条件。

标签: regex

解决方案


我使用命名组和非捕获组以获得更清晰的结果

^(?<Action>\/search)(?:\s+(?<Command>\w+)(?:\s+(?<Query>(?:\w|\s)+))?)?(?:\s+-(?<Genre>\w+))?$

https://regex101.com/r/HL05pu/2


推荐阅读