Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何选择匹配组?_Regex - Fatal编程技术网

Regex 如何选择匹配组?

Regex 如何选择匹配组?,regex,Regex,我有两种可能的模式: 1.2 hello 1.2.3 hello 我想匹配1、2和3,如果后者存在 这似乎是正确的选择,但我的(\d)\.(\d)?(\.(\d)).hello只匹配1.2.3 hello(几乎完美:我得到了四组,但第一、第二和第四组包含了我想要的内容)-第一个测试sting根本不匹配 什么是正确的匹配模式?您的模式包含与数字匹配的(\d)\.(\.(\d))部分,然后是,然后是可选数字(可能是1或0),然后是+数字。因此,它可以匹配1..2 hello,但不能匹配1.2 he

我有两种可能的模式:

1.2 hello
1.2.3 hello
我想匹配
1
2
3
,如果后者存在

这似乎是正确的选择,但我的
(\d)\.(\d)?(\.(\d)).hello
只匹配
1.2.3 hello
(几乎完美:我得到了四组,但第一、第二和第四组包含了我想要的内容)-第一个测试sting根本不匹配


什么是正确的匹配模式?

您的模式包含与数字匹配的
(\d)\.(\.(\d))
部分,然后是
,然后是可选数字(可能是1或0),然后是
+数字。因此,它可以匹配
1..2 hello
,但不能匹配
1.2 hello

您可以将第三组设置为非捕获,并将其设置为可选:

(\d)\.(\d)(?:\.(\d))?\s*hello
          ^^^      ^^

如果您的正则表达式引擎不允许非捕获组,请使用捕获组,只需从组4获取值:

(\d)\.(\d)(\.(\d))?\s*hello

注意,我用
\s*
替换了
之前的
,以匹配零个或多个空格

注意,如果你需要在一行开始匹配这些数字,你可以考虑用“代码>>/CODE”预先确定模式(并且取决于你的正则表达式引擎/工具,<代码> M< /代码>修饰符)。