【问题标题】:Regex anything before, with groups正则表达式之前的任何内容,与组
【发布时间】:2021-08-22 19:47:33
【问题描述】:
在 JS 中,我应该做些什么来匹配并将 > 或 ~ 之前的任何内容放入此正则表达式模式中的 one 组中。
模式:(?<one>.*)(?:>|~)(?<two>.*)https://regex101.com/r/AOY4k0/1/
字符串:
aaa
bbb>ccc
ddd~eee
在本例中,aaa 应进入 <one> 组。
【问题讨论】:
标签:
javascript
regex
regex-group
【解决方案1】:
使用
^(?<one>.*?)(?:(?:>|~)(?<two>.*))?$
替代方案:
^(?<one>.*?)(?:[>~](?<two>.*))?$
见regex proof。
解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?<one> group and capture to "one":
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of "one"
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
(?: group, but do not capture:
--------------------------------------------------------------------------------
> '>'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
~ '~'
--------------------------------------------------------------------------------
) end of grouping
--------------------------------------------------------------------------------
(?<two> group and capture to "two":
--------------------------------------------------------------------------------
.* any character except \n (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of "two"
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
【解决方案2】:
您还可以使用字符类和以[^ 开头的negated character class
^(?<one>[^>~\n]+)(?:[>~](?<two>.*))?$
-
^ 字符串开始
-
(?<one>[^>~\n]+) 组 one 匹配除 > ~ 或换行符以外的任何字符 1 次以上
-
(?:非捕获组
-
[>~] 匹配 > 或 ~
-
(?<two>.*) 组 two 匹配除换行符以外的任何字符 0+ 次
-
)? 关闭群组并将其设为可选
-
$字符串结束
Regex demo