是否可以仅使用一组来获得此正则表达式模式匹配
Is it possible to get this regex pattern match using only one group
所以,这是模式
^(.*)\..*$|^(.*)$
测试字符串:
1. file.tar.gz
2. 文件
对于第一次测试,我会在 'group 1' 中得到 'file.tar',在 'group 2' 中得到 'file'。但我只想要一组输出。我想不出任何其他模式。甚至不确定是否可能。
您需要使第一个 .*
惰性化,并在可选组中使用否定字符 class:
^(.*?)(?:\.[^.]*)?$
详情:
^
- 字符串开头
(.*?)
- 任何 0+ 个字符尽可能少
(?:\.[^.]*)?
- 可选的非捕获组匹配 1 或 0 个序列:
\.
- 一个点
[^.]*
- .
以外的 0+ 个字符
$
- 字符串结尾。
另一种使用双重否定且没有捕获组的方法:
^.*(?![^.])
(从字符串开头开始的任意数量的字符,后面没有不是点的字符。)
"not followed by a character that isn't a dot" <=> "followed by a dot or the end of the string"
所以,这是模式
^(.*)\..*$|^(.*)$
测试字符串: 1. file.tar.gz 2. 文件
对于第一次测试,我会在 'group 1' 中得到 'file.tar',在 'group 2' 中得到 'file'。但我只想要一组输出。我想不出任何其他模式。甚至不确定是否可能。
您需要使第一个 .*
惰性化,并在可选组中使用否定字符 class:
^(.*?)(?:\.[^.]*)?$
详情:
^
- 字符串开头(.*?)
- 任何 0+ 个字符尽可能少(?:\.[^.]*)?
- 可选的非捕获组匹配 1 或 0 个序列:\.
- 一个点[^.]*
-.
以外的 0+ 个字符
$
- 字符串结尾。
另一种使用双重否定且没有捕获组的方法:
^.*(?![^.])
(从字符串开头开始的任意数量的字符,后面没有不是点的字符。)
"not followed by a character that isn't a dot" <=> "followed by a dot or the end of the string"