用于捕获和修复版本号的正则表达式

Regular expression to capture & fix a version number

我正在尝试创建一个正则表达式来提取版本号。由于提供这些版本字符串的来源大多不可靠,我需要清理这些值。

版本是一个数字或仅由一个点分隔的一组数字。一旦链条断了,我就停止捕获,并保留到目前为止捕获的内容。

测试用例:

Foo 1.2.3.4.5 bar --> Should capture 1.2.3.4.5
Foo 111111.2..3.4.5 bar --> Should capture 111111.2
Foo 10.. bar --> Should capture 10
1.2.3 aaa --> Should capture 1.2.3
aaa 1.2.3 --> Should capture 1.2.3
1.23 --> Should capture 1.23

我找到了一些例子,但 none 符合我的边缘情况(见上面概述的第三种情况)。

到目前为止我有:

/(\d+(?:\.\d+)+)/i

但它并没有涵盖我所有的案例...我将它与 PHP (pcre) 一起使用。

我会选择以下内容:

\d+(?:\.\d+)*

这匹配一个数字,后面可以跟任意数量的[点和数字]。

与您的正则表达式的不同之处在于使用了 *,它可以捕获由单个数字组成的版本。

我还删除了可能毫无用处的外部分组括号。

解决方案一:

Regex demo

正则表达式: ^[^\d]+\s*\K(\d+(?:\.\d+)*)

1. ^ start of string.

2. [^\d]+\s* match all except digit then spaces

3. \K will reset the match.

4. (\d+(?:\.\d+)*) this will match digits and then existence of zero or more patterns of . and digits

方案二:

Regex demo

正则表达式: ^Foo\s*\K(\d+(?:\.\d+)*)

1. ^ start of string.

2. Foo\s* this will match Foo and spaces

3. \K will reset the match.

4. (\d+(?:\.\d+)*) this will match digits and then existence of zero or more patterns of . and digits