以下是一些使用正则表达式 (Regex) 从字符串中提取版本号的通用解决方案。
正则表达式的解释(\d+\.\d+\.\d+\.\d+)
:
(
开始第一个捕获组
\d
匹配一个数字(相当于 [0-9])
+
匹配前一个令牌一次到无限次,尽可能多次,根据需要回馈(贪婪)
\.
从字面上匹配字符.
(区分大小写)
)
关闭第一个捕获组
因此,对于通常使用 format 的版本号,X.X.X.X
只需根据您有兴趣捕获的版本号组件的数量重复 Regex 模式多次即可。
- 最简单但最不灵活的解决方案是寻找您需要的确切模式。此方法查找标准的 4 组件版本号。要仅查找 2 部分版本号,您可以将 Regex 更改为
(\d+\.\d+)
/// <summary>
/// Extracts a version from the given input.
/// </summary>
/// <param name="input">
/// String that may contain a valid 4-component version in the format X.X.X.X.
/// <para>
/// e.g. 1.0.0.0 or 0.0.17.95
/// </para>
/// </param>
/// <returns>Version or null.</returns>
public string ExtractVersionNumber(string input)
{
var regex = new Regex(@"(\d+\.\d+\.\d+\.\d+)");
var match = regex.Match(input);
return match.Success ? match.Value : null;
}
- 更灵活的解决方案是指定是否需要版本号的构建和修订号组件。
/// <summary>
/// Extracts a version number from the given input.
/// </summary>
/// <param name="input">
/// String that may contain a valid version.
/// <para>
/// e.g. 1.0.0.0 or 0.0.17.95
/// </para>
/// </param>
/// <param name="requireBuild">
/// Indicates whether the build component of the version is required.
/// <para>
/// e.g. 1.0.0 or 0.0.17
/// </para>
/// </param>
/// <param name="requireRevision">
/// Indicates whether the revision component of the version is required.
/// <para>
/// e.g. 1.0.0.0 or 0.0.17.95
/// </para>
/// </param>
/// <returns>Version or null.</returns>
public string ExtractVersionNumber(string input, bool requireBuild = true, bool requireRevision = true)
{
var pattern = @"\d+\.\d+";
if (requireBuild)
{
pattern += @"\.\d+";
}
if (requireRevision)
{
pattern += @"\.\d+";
}
var regex = new Regex($"({pattern})");
var match = regex.Match(input);
return match.Success ? match.Value : null;
}
- 另一种灵活的方法是指定所需的版本号组件的数量。
/// <summary>
/// Extracts a version from the given input.
/// </summary>
/// <param name="input">
/// String that may contain a valid version number.
/// </param>
/// <param name="componentsRequired">
/// Number of version components required. Defaults to 4.
/// <para>Valid values: 4, 3, 2.</para>
/// <para>4 components example: 1.0.0.0 or 0.1.17.95</para>
/// <para>3 components example: 1.0.0 or 0.1.17</para>
/// <para>2 components example: 1.0 or 0.1</para>
/// </param>
/// <returns>Version or null.</returns>
public string ExtractVersionNumber(string input, int componentsRequired = 4)
{
string pattern;
switch (componentsRequired)
{
case 4:
pattern = @"(\d+\.\d+\.\d+\.\d+)";
break;
case 3:
pattern = @"(\d+\.\d+\.\d+)";
break;
case 2:
pattern = @"(\d+\.\d+)";
break;
default:
throw new ArgumentOutOfRangeException(nameof(componentsRequired), "Valid values: 4, 3, 2");
}
var regex = new Regex(pattern);
var match = regex.Match(input);
return match.Success ? match.Value : null;
}